Created
June 14, 2018 21:46
-
-
Save Cibernomadas/f1506147e7caf6e0094ba0bcb40687bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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