Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(auth): enhance logout process and add QR auto-refresh functionality

Aldino Kemal1e90256bc9b4
diff --git a/readme.md b/readme.md
index eadbe7bb..27eb8e60 100644
--- a/readme.md
+++ b/readme.md
@@ -4,7 +4,7 @@
<!-- markdownlint-disable-next-line MD033 -->
<img src="src/views/assets/gowa.svg" alt="GoWA Logo" width="200" height="200">
-## Golang WhatsApp - Built in Go for efficient memory use
+## Golang WhatsApp - Built with Go for efficient memory use
</div>
diff --git a/src/usecase/app.go b/src/usecase/app.go
index d16093d0..afd49e23 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -11,9 +11,11 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
fiberUtils "github.com/gofiber/fiber/v2/utils"
+ _ "github.com/mattn/go-sqlite3"
"github.com/sirupsen/logrus"
"github.com/skip2/go-qrcode"
"go.mau.fi/libsignal/logger"
@@ -38,16 +40,38 @@ func (service serviceApp) Login(_ context.Context) (response domainApp.LoginResp
return response, pkgError.ErrWaCLI
}
+ // [DEBUG] Log database state before login
+ logrus.Info("[DEBUG] Starting login process...")
+ devices, dbErr := service.db.GetAllDevices(context.Background())
+ if dbErr != nil {
+ logrus.Errorf("[DEBUG] Error getting devices before login: %v", dbErr)
+ } else {
+ logrus.Infof("[DEBUG] Devices before login: %d found", len(devices))
+ for _, device := range devices {
+ logrus.Infof("[DEBUG] Device ID: %s, PushName: %s", device.ID.String(), device.PushName)
+ }
+ }
+
+ // [DEBUG] Log client state
+ if service.WaCli.Store.ID != nil {
+ logrus.Infof("[DEBUG] Client has existing store ID: %s", service.WaCli.Store.ID.String())
+ } else {
+ logrus.Info("[DEBUG] Client has no store ID")
+ }
+
// Disconnect for reconnecting
service.WaCli.Disconnect()
chImage := make(chan string)
+ logrus.Info("[DEBUG] Attempting to get QR channel...")
ch, err := service.WaCli.GetQRChannel(context.Background())
if err != nil {
+ logrus.Errorf("[DEBUG] GetQRChannel failed: %v", err)
logrus.Error(err.Error())
// This error means that we're already logged in, so ignore it.
if errors.Is(err, whatsmeow.ErrQRStoreContainsID) {
+ logrus.Info("[DEBUG] Error is ErrQRStoreContainsID - attempting to connect")
_ = service.WaCli.Connect() // just connect to websocket
if service.WaCli.IsLoggedIn() {
return response, pkgError.ErrAlreadyLoggedIn
@@ -57,6 +81,7 @@ func (service serviceApp) Login(_ context.Context) (response domainApp.LoginResp
return response, pkgError.ErrQrChannel
}
} else {
+ logrus.Info("[DEBUG] QR channel obtained successfully")
go func() {
for evt := range ch {
response.Code = evt.Code
@@ -71,12 +96,15 @@ func (service serviceApp) Login(_ context.Context) (response domainApp.LoginResp
time.Sleep(response.Duration * time.Second)
err := os.Remove(qrPath)
if err != nil {
- logrus.Error("error when remove qrImage file", err.Error())
+ // Only log if it's not a "file not found" error
+ if !os.IsNotExist(err) {
+ logrus.Error("error when remove qrImage file", err.Error())
+ }
}
}()
chImage <- qrPath
} else {
- logrus.Error("error when get qrCode", evt.Event)
+ logrus.Error("error when get qrCode", evt.Event, evt.Error)
}
}
}()
@@ -117,8 +145,70 @@ func (service serviceApp) LoginWithCode(ctx context.Context, phoneNumber string)
return loginCode, nil
}
-func (service serviceApp) Logout(ctx context.Context) (err error) {
- // delete history
+func (service *serviceApp) Logout(ctx context.Context) (err error) {
+ // [DEBUG] Log database state before logout
+ logrus.Info("[DEBUG] Starting logout process...")
+ devices, dbErr := service.db.GetAllDevices(ctx)
+ if dbErr != nil {
+ logrus.Errorf("[DEBUG] Error getting devices before logout: %v", dbErr)
+ } else {
+ logrus.Infof("[DEBUG] Devices before logout: %d found", len(devices))
+ for _, device := range devices {
+ logrus.Infof("[DEBUG] Device ID: %s, PushName: %s", device.ID.String(), device.PushName)
+ }
+ }
+
+ // [DEBUG] Call WhatsApp client logout first to disconnect from server
+ logrus.Info("[DEBUG] Calling WhatsApp client logout...")
+ err = service.WaCli.Logout(ctx)
+ if err != nil {
+ logrus.Errorf("[DEBUG] WhatsApp logout failed: %v", err)
+ // Continue with cleanup even if logout fails
+ } else {
+ logrus.Info("[DEBUG] WhatsApp logout completed successfully")
+ }
+
+ // [DEBUG] Verify devices after logout
+ devices, dbErr = service.db.GetAllDevices(ctx)
+ if dbErr != nil {
+ logrus.Errorf("[DEBUG] Error getting devices after logout: %v", dbErr)
+ } else {
+ logrus.Infof("[DEBUG] Devices after logout: %d found", len(devices))
+ }
+
+ // Disconnect current client
+ service.WaCli.Disconnect()
+
+ // Clean up database by removing the file
+ // This prevents foreign key constraint issues on next login
+ dbPath := strings.TrimPrefix(config.DBURI, "file:")
+ if strings.Contains(dbPath, "?") {
+ dbPath = strings.Split(dbPath, "?")[0]
+ }
+
+ logrus.Infof("[DEBUG] Removing database file to prevent FK constraints: %s", dbPath)
+ if err := os.Remove(dbPath); err != nil {
+ if !os.IsNotExist(err) {
+ logrus.Errorf("[DEBUG] Error removing database file: %v", err)
+ } else {
+ logrus.Info("[DEBUG] Database file already removed")
+ }
+ } else {
+ logrus.Info("[DEBUG] Database file removed successfully")
+ }
+
+ // Reinitialize database and client to avoid restart requirement
+ logrus.Info("[DEBUG] Reinitializing database and client...")
+ newDB := whatsapp.InitWaDB(ctx)
+ newCli := whatsapp.InitWaCLI(ctx, newDB)
+
+ // Update service references
+ service.db = newDB
+ service.WaCli = newCli
+
+ logrus.Info("[DEBUG] Database and client reinitialized successfully")
+
+ // delete history files
files, err := filepath.Glob(fmt.Sprintf("./%s/history-*", config.PathStorages))
if err != nil {
return err
@@ -130,6 +220,7 @@ func (service serviceApp) Logout(ctx context.Context) (err error) {
return err
}
}
+
// delete qr images
qrImages, err := filepath.Glob(fmt.Sprintf("./%s/scan-*", config.PathQrCode))
if err != nil {
@@ -158,8 +249,9 @@ func (service serviceApp) Logout(ctx context.Context) (err error) {
}
}
- err = service.WaCli.Logout(ctx)
- return
+ logrus.Info("[DEBUG] Logout process completed successfully")
+ logrus.Info("[DEBUG] Application is ready for next login without restart")
+ return nil
}
func (service serviceApp) Reconnect(_ context.Context) (err error) {
diff --git a/src/views/components/AppLogin.js b/src/views/components/AppLogin.js
index 76de2d65..2265b09a 100644
--- a/src/views/components/AppLogin.js
+++ b/src/views/components/AppLogin.js
@@ -7,6 +7,7 @@ export default {
return {
login_link: '',
login_duration_sec: 0,
+ countdown_timer: null,
}
},
methods: {
@@ -18,6 +19,9 @@ export default {
$('#modalLogin').modal({
onApprove: function () {
return false;
+ },
+ onHidden: () => {
+ this.stopCountdown();
}
}).modal('show');
} catch (err) {
@@ -26,18 +30,57 @@ export default {
},
async submitApi() {
try {
+ // Stop existing countdown before making new request
+ this.stopCountdown();
+
let response = await window.http.get(`app/login`)
let results = response.data.results;
this.login_link = results.qr_link;
this.login_duration_sec = results.qr_duration;
+
+ // Start countdown after successful API call
+ this.startCountdown();
} catch (error) {
if (error.response) {
throw Error(error.response.data.message)
}
throw Error(error.message)
}
+ },
+ startCountdown() {
+ // Clear any existing timer
+ this.stopCountdown();
+
+ this.countdown_timer = setInterval(() => {
+ if (this.login_duration_sec > 0) {
+ this.login_duration_sec--;
+ } else {
+ // Auto refresh when countdown reaches 0
+ this.autoRefresh();
+ }
+ }, 1000);
+ },
+ stopCountdown() {
+ if (this.countdown_timer) {
+ clearInterval(this.countdown_timer);
+ this.countdown_timer = null;
+ }
+ },
+ async autoRefresh() {
+ try {
+ console.log('QR Code expired, auto refreshing...');
+ await this.submitApi();
+ } catch (error) {
+ console.error('Auto refresh failed:', error);
+ this.stopCountdown();
+ showErrorInfo(error);
+ }
}
},
+ beforeUnmount() {
+ // Clean up timer when component is destroyed
+ this.stopCountdown();
+ },
template: `
<div class="green card" @click="openModal" style="cursor: pointer">
<div class="content">
@@ -63,7 +106,8 @@ export default {
<div class="ui header">Please scan to connect</div>
<p>Open Setting > Linked Devices > Link Device</p>
<div style="padding-top: 50px;">
- <i>Refresh QR Code in {{ login_duration_sec }} seconds to avoid link expiration</i>
+ <i v-if="login_duration_sec > 0">QR Code expires in {{ login_duration_sec }} seconds (auto-refreshing)</i>
+ <i v-else class="ui active inline">Refreshing QR Code...</i>
</div>
</div>
</div>