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
|
package handlers
import (
"encoding/json"
"net/http"
"github.com/boozec/rahanna/api/auth"
"github.com/boozec/rahanna/api/database"
"golang.org/x/crypto/bcrypt"
)
func RegisterUser(w http.ResponseWriter, r *http.Request) {
var user database.User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
user.Password = string(hashedPassword)
db, _ := database.GetDb()
result := db.Create(&user)
if result.Error != nil {
http.Error(w, result.Error.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func LoginUser(w http.ResponseWriter, r *http.Request) {
var inputUser database.User
err := json.NewDecoder(r.Body).Decode(&inputUser)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var storedUser database.User
db, _ := database.GetDb()
result := db.Where("username = ?", inputUser.Username).First(&storedUser)
if result.Error != nil {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
err = bcrypt.CompareHashAndPassword([]byte(storedUser.Password), []byte(inputUser.Password))
if err != nil {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
token, err := auth.GenerateJWT(storedUser.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(map[string]string{"token": token})
}
|