-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthController.go
84 lines (56 loc) · 1.57 KB
/
AuthController.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package controllers
import (
"net/http"
"main.go/database"
"main.go/app/models"
"github.com/labstack/echo"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func Login(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")
db := database.Connect()
userModel := models.UserModel{
Db: db,
}
user := userModel.FindUser(username)
isAuth := CheckPasswordHash(password, user.Password)
if isAuth == true {
err := AuthLogin(c, user)
if err != nil {
panic(err.Error())
}
return c.Redirect(http.StatusSeeOther, "/")
}
defer db.Close()
return c.Render(http.StatusOK, "login.html", map[string]interface{}{"error": "Login Failed"})
}
func Logout(c echo.Context) error {
err := AuthLogout(c)
if err != nil {
panic(err.Error())
}
return c.Redirect(http.StatusSeeOther, "/user/login")
}
func Register(c echo.Context) error {
db := database.Connect()
username := c.FormValue("username")
email := c.FormValue("email")
password := c.FormValue("password")
sqlRes, err := db.Prepare("INSERT INTO users(username , email, password) VALUES(? ,?, ?)")
if err != nil {
panic(err.Error())
}
hash, _ := HashPassword(password)
sqlRes.Exec(username, email, hash)
defer db.Close()
return c.Redirect(http.StatusSeeOther, "/user/login")
}