Skip to content

Instantly share code, notes, and snippets.

@Cibernomadas
Created June 14, 2018 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cibernomadas/f1506147e7caf6e0094ba0bcb40687bd to your computer and use it in GitHub Desktop.
Save Cibernomadas/f1506147e7caf6e0094ba0bcb40687bd to your computer and use it in GitHub Desktop.
func LoginFn(c *gin.Context) {
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
var user models.User
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
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