Skip to content

Commit

Permalink
fix: session destroy and email validation.
Browse files Browse the repository at this point in the history
  • Loading branch information
puni9869 committed May 19, 2024
1 parent bc94ea8 commit d31671e
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 34 deletions.
82 changes: 59 additions & 23 deletions server/auth/login.go
Original file line number Diff line number Diff line change
@@ -1,58 +1,94 @@
package auth

import (
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/puni9869/pinmyblogs/models"
"github.com/puni9869/pinmyblogs/pkg/database"
"github.com/puni9869/pinmyblogs/pkg/logger"
"net/http"
)

const userkey = "user"

func LoginPost(c *gin.Context) {
session := sessions.Default(c)
username := c.PostForm("email")
log := logger.NewLogger()

email := c.PostForm("email")
password := c.PostForm("password")

// Validate form input and check authentication
if username != "hello" || password != "itsme" {
c.HTML(http.StatusOK, "login.tmpl", nil)
return
if email == "" || password == "" {
log.WithField("email", email).Error("Empty password or email.")
c.HTML(http.StatusBadRequest, "login.tmpl", gin.H{"HasError": true, "Error": "Invalid email or password."})
c.Abort()
}

var user *models.User
result := database.Db().First(&user, "email = ?", email)
if result.Error != nil {
log.WithField("email", email).WithError(result.Error).Error("Invalid email or password. Database error")
c.HTML(http.StatusUnauthorized, "login.tmpl", gin.H{"HasError": true, "Error": "Invalid email or password"})
c.Abort()
}

// Save the username in the session
session.Set(userkey, username)
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
session := sessions.Default(c)
currentlyLoggedIn := session.Get(userkey)
log.WithField("email", email).Info("login found ", currentlyLoggedIn)
if currentlyLoggedIn == nil || currentlyLoggedIn != email {
session.Set(userkey, email)
log.WithField("email", email).Info("setting user", currentlyLoggedIn)
if err := session.Save(); err != nil {
log.WithField("email", email).WithError(result.Error).Error("Unable to save session.")
c.HTML(http.StatusInternalServerError, "login.tmpl", gin.H{"HasError": true, "Error": "Something went wrong. We are working on it."})
c.Abort()
}
log.WithField("email", email).Info("set user", currentlyLoggedIn)
}
fmt.Println(user, "user currently logged in")
// Redirect to the home route upon successful login
c.HTML(http.StatusAccepted, "home.tmpl", nil)
c.HTML(http.StatusOK, "home.tmpl", nil)
}

func LoginGet(c *gin.Context) {
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)
c.HTML(http.StatusOK, "login.tmpl", nil)
return

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

View workflow job for this annotation

GitHub Actions / checks

S1023: redundant `return` statement (gosimple)
// 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)
}

// Logout is the handler called for the user to log out.
func Logout(c *gin.Context) {
log := logger.NewLogger()

session := sessions.Default(c)
user := session.Get(userkey)
if user == nil {
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 err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
c.Abort()
if len(sessionId) != 0 {
log.WithField("session", user).Info("session id found")
res := database.Db().Table("sessions").Where("id = ?", sessionId)
log.Info("rows affected ", res.RowsAffected)
if res.Error != nil {
log.WithField("session", user).WithError(res.Error).Error("failed to delete the session")
}
}
c.HTML(http.StatusOK, "index.tmpl", nil)
c.Abort()
c.Redirect(http.StatusTemporaryRedirect, "/login")
}
8 changes: 4 additions & 4 deletions server/middlewares/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

const (
ContextKey = "pinmyblogs"
contextKey = "pinmyblogs"
formKey = "__form"
)

Expand All @@ -20,7 +20,7 @@ func GetForm(c *gin.Context) any {
}

func GetContext(c *gin.Context) gin.H {
if ctx, ok := c.Get(ContextKey); ok {
if ctx, ok := c.Get(contextKey); ok {
return ctx.(map[string]any)
}
return nil
Expand All @@ -32,12 +32,12 @@ func BindForm[T any](_ T) gin.HandlerFunc {
data := make(map[string]any)
data["HasError"] = false
var theObj = new(T) // create a new form obj for every request but not use obj directly
c.Set(ContextKey, data)
c.Set(contextKey, data)
errs := c.ShouldBindWith(theObj, binding.Form)
formbinding.FillContext(theObj, data)
if errs != nil {
data = formbinding.Errorf(make(gin.H), errs.(validator.ValidationErrors))
c.Set(ContextKey, data)
c.Set(contextKey, data)
}
c.Set(formKey, theObj)
}
Expand Down
8 changes: 4 additions & 4 deletions templates/auth/login.tmpl
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{{template "layout/base" .}}
<div class="bg-white h-full">
<div class="flex min-h-full flex-col justify-center px-6 py-10 lg:px-8">
<div class="flex min-h-full flex-col justify-center px-6 py-7 lg:px-8">
<div class="sm:mx-auto sm:w-full sm:max-w-sm">
<a href="/"><img class="mx-auto h-20 w-auto" src="statics/icons/favicon.svg" alt="pinmyblogs.com"></a>
<h2 class="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">Sign in to your account</h2>
<h2 class="mt-6 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">Sign in to your account</h2>
</div>

<div class="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
<div class="mt-5 sm:mx-auto sm:w-full sm:max-w-sm">
<p class="text-base text-red-600 text-center {{if .HasError}}visible{{else}}hidden{{end}}">{{.Error}}</p>
<form class="space-y-6" action="/login" method="POST">
<div>
<label for="email" class="block text-sm font-medium leading-6 text-gray-900">Email address</label>
<div class="mt-2">
<input id="email" name="email" type="text" autofocus autocomplete="email" required class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 px-3 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
</div>
</div>

<div>
<div class="flex items-center justify-between">
<label for="password" class="block text-sm font-medium leading-6 text-gray-900">Password</label>
Expand Down
6 changes: 3 additions & 3 deletions templates/auth/signup.tmpl
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{{template "layout/base" .}}
<div class="bg-white h-full">
<div class="flex min-h-full flex-col justify-center px-6 py-10 lg:px-8">
<div class="flex min-h-full flex-col justify-center px-6 py-7 lg:px-8">
<div class="sm:mx-auto sm:w-full sm:max-w-sm">
<a href="/"><img class="mx-auto h-20 w-auto" src="statics/icons/favicon.svg" alt="pinmyblogs.com" /></a>
<h2 class="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">Sign up for new account</h2>
<h2 class="mt-6 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">Sign up for new account</h2>
</div>
<div class="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
<div class="mt-5 sm:mx-auto sm:w-full sm:max-w-sm">
<form class="space-y-6" action="/signup" method="POST">
<div>
<label for="email" class="block text-sm font-medium leading-6 text-gray-900">Email address</label>
Expand Down

0 comments on commit d31671e

Please sign in to comment.