Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
func LoginFn(c *gin.Context) {
user := models.User{}
session := sessions.Default(c)
u := session.Get("user")
if u != nil {
user = u.(models.User)
}
if u != nil && user.IsAuthenticated {
// There is no need to see login page
// Showing index
c.HTML(http.StatusOK, "index", gin.H{
"title": "Hi! GoBlog.",
"user": user,
})
return
}
// The user is not authenticated
if c.Request.Method == http.MethodGet { // Serve login page
c.HTML(http.StatusOK, "login", gin.H{
"title": "Hi! GoBlog.",
})
} else if c.Request.Method == http.MethodPost { // Process login
dbc, exist := c.Get("db")
if !exist {
c.HTML(http.StatusOK, "login", gin.H{
"title": "Hi! GoBlog.",
"error": "We've got an internal error, please try later.",
})
return
}
var login models.LoginForm
db := dbc.(*gorm.DB)
if err := c.ShouldBind(&login); err == nil {
db.Where(&models.User{Username: login.Username}).First(&user)
if user.CheckPassword(login.Password) {
user.IsAuthenticated = true
session.Set("user", user)
if err = session.Save(); err != nil {
c.HTML(http.StatusOK, "login", gin.H{
"title": "Hi! GoBlog.",
"error": "Internal error. Please try later",
})
return
}
c.HTML(http.StatusOK, "index", gin.H{
"title": "Hi! GoBlog.",
"user": user,
})
} else {
c.HTML(http.StatusOK, "login", gin.H{
"title": "Hi! GoBlog.",
"error": "Username or Password incorrect, please try again.",
})
}
} else {
c.HTML(http.StatusOK, "login", gin.H{
"title": "Hi! GoBlog.",
"error": "Required fields are not provided correctly.",
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment