Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package api
- import (
- "github.com/dchest/uniuri"
- "github.com/gin-gonic/gin"
- "mastersapi/database"
- "mastersapi/models"
- "net/http"
- "strings"
- "time"
- )
- type LoginForm struct {
- Email string `json:"email" binding:"required,email"`
- Password string `json:"password" binding:"required"`
- }
- func Login(c *gin.Context) {
- loginForm := LoginForm{}
- if err := c.ShouldBindJSON(&loginForm); err != nil {
- FailureWithMessage(c, http.StatusBadRequest, err.Error())
- return
- }
- account := models.Account{}
- count := database.Get().Where(&models.Account{Email: loginForm.Email}).Take(&account).RowsAffected
- if count > 0 && account.CheckPassword(loginForm.Password) {
- key := strings.ToUpper(uniuri.NewLen(32))
- session := models.AccountSession{
- AccountId: account.ID,
- Key: key,
- ExpiresAt: time.Now().Unix() + 3600*24*1000,
- }
- err := database.Get().Create(&session).Error
- if err != nil {
- FailureWithMessage(c, 500, err.Error())
- return
- } else {
- if account.LoginErrors > 0 {
- account.LoginErrors = 0
- database.Get().Save(&account)
- }
- Success(c, http.StatusOK, gin.H{"key": session.Key, "email": account.Email})
- return
- }
- } else {
- if account.LoginErrors > 5 {
- sleep := 2 * time.Second
- time.Sleep(time.Duration(sleep))
- }
- account.LoginErrors++
- err := database.Get().Save(&account).Error
- if err != nil {
- FailureWithMessage(c, http.StatusInternalServerError, err.Error())
- } else {
- Failure(c, 403)
- }
- }
- }
- func Logout(c *gin.Context) {
- sessionID := c.GetInt("session_id")
- session := models.AccountSession{}
- database.Get().Take(&session, sessionID)
- database.Get().Delete(&session)
- Success(c, http.StatusOK, gin.H{})
- }
- type RegisterForm struct {
- Email string `json:"email" binding:"required,email"`
- Password string `json:"password" binding:"required"`
- }
- func Register(c *gin.Context) {
- rform := RegisterForm{}
- if err := c.ShouldBindJSON(&rform); err != nil {
- FailureWithMessage(c, http.StatusBadRequest, err.Error())
- return
- }
- account := models.Account{}
- account.Email = rform.Email
- account.CreatedAt = time.Now().Unix()
- account.SetPassword(rform.Password)
- tx := database.Get().First(&models.Account{}, models.Account{Email:account.Email})
- notFound := tx.RecordNotFound()
- err := tx.Error
- if !notFound && err == nil {
- FailureWithMessage(c, http.StatusBadRequest, "User with email " + account.Email + " already exists")
- return
- }
- err = database.Get().Create(&account).Error
- if err != nil {
- FailureWithMessage(c, http.StatusInternalServerError, err.Error())
- } else {
- Success(c, http.StatusOK, gin.H{"email": rform.Email})
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement