Skip to content

Commit

Permalink
fix: logout completely and kill all the session.
Browse files Browse the repository at this point in the history
  • Loading branch information
puni9869 committed May 20, 2024
1 parent 006a8d1 commit 23dc2ec
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 32 deletions.
8 changes: 8 additions & 0 deletions models/session.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package models

import "gorm.io/gorm"

type Session struct {
gorm.Model
data string

Check failure on line 7 in models/session.go

View workflow job for this annotation

GitHub Actions / checks

field `data` is unused (unused)
}
4 changes: 3 additions & 1 deletion models/user.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package models

import (
"github.com/google/uuid"
"time"

"github.com/google/uuid"
)

type User struct {
Expand All @@ -19,4 +20,5 @@ type User struct {
ActivatedAt time.Time // Uses time.Time for nullable time fields
CreatedAt time.Time // Automatically managed by GORM for creation time
UpdatedAt time.Time // Automatically managed by GORM for update time
AlternateEmail string // Can be used for changing emailid
}
6 changes: 4 additions & 2 deletions pkg/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package database
import (
"database/sql"
"fmt"
"github.com/google/uuid"
"gorm.io/driver/sqlite"
"log"
"os"
"sync"
"time"

"github.com/google/uuid"
"gorm.io/driver/sqlite"

sqliteGo "github.com/mattn/go-sqlite3"
"github.com/puni9869/pinmyblogs/models"
"github.com/puni9869/pinmyblogs/pkg/config"
Expand Down Expand Up @@ -115,6 +116,7 @@ func RegisterModels(db *gorm.DB) {
// m is list of all the database models
m := []any{
&models.User{},
&models.Session{},
}
if err := db.AutoMigrate(m...); err != nil {
panic(err)
Expand Down
65 changes: 43 additions & 22 deletions server/auth/login.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package auth

import (
"fmt"
"net/http"

"github.com/gin-contrib/sessions"
Expand Down Expand Up @@ -48,22 +47,35 @@ func LoginPost(c *gin.Context) {
}
log.WithField("email", email).Info("set user", currentlyLoggedIn)
}
fmt.Println(user, "user currently logged in")
log.WithField("user", user).Info("user currently logged in")
// Redirect to the home route upon successful login
c.HTML(http.StatusOK, "home.tmpl", nil)
c.Redirect(http.StatusPermanentRedirect, "/")
c.Abort()
return

Check failure on line 54 in server/auth/login.go

View workflow job for this annotation

GitHub Actions / checks

S1023: redundant `return` statement (gosimple)
}

func LoginGet(c *gin.Context) {
c.HTML(http.StatusOK, "login.tmpl", nil)
// session := sessions.Default(c)
// user := session.Get(userkey)
//
// if user == nil {
// c.HTML(http.StatusOK, "login.tmpl", nil)
// return
// }
//
// c.HTML(http.StatusAccepted, "home.tmpl", nil)
log := logger.NewLogger()

session := sessions.Default(c)
currentlyLoggedIn := session.Get(userkey)

if currentlyLoggedIn == nil || len(currentlyLoggedIn.(string)) == 0 {
c.HTML(http.StatusOK, "login.tmpl", nil)
c.Abort()
return
}
var user *models.User
result := database.Db().First(&user, "email = ?", currentlyLoggedIn)
if result.Error != nil {
log.WithField("email", currentlyLoggedIn).WithError(result.Error).Error("User not found in database. Database error")
c.HTML(http.StatusUnauthorized, "login.tmpl", gin.H{"HasError": true, "Error": "Invalid email or password"})
c.Abort()
return
}
log.WithField("email", currentlyLoggedIn).Info("loggedIn user")
c.HTML(http.StatusOK, "home.tmpl", nil)
c.Abort()
}

// Logout is the handler called for the user to log out.
Expand All @@ -76,19 +88,28 @@ func Logout(c *gin.Context) {
log.WithField("user", user).Info("Redirecting to login page. Session not found")
c.Redirect(http.StatusTemporaryRedirect, "/login")
c.Abort()
return
}
sessionId := session.ID()
log.Info("session id ", sessionId)

session.Clear()
session.Delete(userkey)
if len(sessionId) != 0 {
sId := session.ID()

if len(sId) != 0 {
log.WithField("session", user).Info("session id found")
res := database.Db().Table("sessions").Where("id = ?", sessionId)
log.Info("rows affected ", res.RowsAffected)

session.Delete(sId)
session.Set(userkey, nil)

var s *models.Session
res := database.Db().Delete(&s, "id = ?", sId)
if res.Error != nil {
log.WithField("session", user).WithError(res.Error).Error("failed to delete the session")
log.WithField("session", user).WithError(res.Error).Error("failed to delete the session from database")
}

log.Info("rows affected ", res.RowsAffected)

if err := session.Save(); err != nil {
log.WithError(err).Error("Unable to delete the session.")
c.HTML(http.StatusInternalServerError, "login.tmpl", gin.H{"HasError": true, "Error": "Something went wrong. We are working on it."})
c.Abort()
}
}
c.Redirect(http.StatusTemporaryRedirect, "/login")
Expand Down
13 changes: 7 additions & 6 deletions server/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/puni9869/pinmyblogs/server/auth"
"github.com/puni9869/pinmyblogs/server/home"
"github.com/puni9869/pinmyblogs/server/middlewares"
"github.com/puni9869/pinmyblogs/server/setting"
"github.com/puni9869/pinmyblogs/types/forms"
)

Expand All @@ -31,17 +32,17 @@ func RegisterRoutes(r *gin.Engine, sessionStore session.Store) {
// auth urls
r.GET("/login", auth.LoginGet)
r.POST("/login", auth.LoginPost)
r.GET("/logout", auth.Logout)
r.Any("/logout", auth.Logout)

authRouters := r.Group("")
{
authRouters.Use(middlewares.AuthRequired)
authRouters.GET("/home", home.Home)
//authRouters.GET("/favourite", home.Favourite)
//authRouters.GET("/archived", home.Archived)
//authRouters.GET("/trash", home.Trash)
authRouters.Any("/home", home.Home)
authRouters.GET("/favourite", home.Favourite)
authRouters.GET("/archived", home.Archived)
authRouters.GET("/trash", home.Trash)
//// setting handler
//authRouters.GET("/setting", setting.Setting)
authRouters.Any("/setting", setting.Setting)
// navbar handler
authRouters.GET("/", home.Home)
}
Expand Down
3 changes: 2 additions & 1 deletion server/setting/setting.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package setting

import (
"github.com/gin-gonic/gin"
"net/http"

"github.com/gin-gonic/gin"
)

func Setting(c *gin.Context) {
Expand Down

0 comments on commit 23dc2ec

Please sign in to comment.