Created
June 26, 2018 21:13
-
-
Save Cibernomadas/4075f2024ac76ddfb597720422258e82 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) { | |
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