-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts.go
190 lines (155 loc) · 5.52 KB
/
accounts.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package models
import (
u "github.com/PierreBougon/Bym-BackEnd/app/utils"
"os"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
)
/*
JWT claims struct
*/
type Token struct {
UserId uint
TokenVersion uint
jwt.StandardClaims
}
//a struct to rep user account
type Account struct {
Model
Email string `json:"email",gorm:"type:text;unique;not null"`
Password string `json:"password"`
TokenVersion uint `json:"token_version"`
Picture string `json:"picture"`
Playlists []Playlist `gorm:"ForeignKey:UserId"`
FollowedPlaylists []*Playlist `gorm:"many2many:account_playlist"`
Acl []PlaylistAccessControl `gorm:"ForeignKey:UserId"`
}
func (account *Account) ValidatePassword() (map[string]interface{}, bool) {
if len(account.Password) < 6 {
return u.Message(false, "Password with more than 6 characters is required"), false
}
return nil, true
}
//Validate incoming user details...
func (account *Account) Validate() (map[string]interface{}, bool) {
if !strings.Contains(account.Email, "@") {
return u.Message(false, "Email address is required"), false
}
resp, passed := account.ValidatePassword()
if !passed {
return resp, false
}
//Email must be unique
temp := &Account{}
//check for errors and duplicate emails
err := GetDB().Table("accounts").Where("email = ?", account.Email).First(temp).Error
if err != nil && err != gorm.ErrRecordNotFound {
return u.Message(false, "Connection error. Please retry"), false
}
if temp.Email != "" {
return u.Message(false, "Email address already in use by another user."), false
}
return u.Message(false, "Requirement passed"), true
}
func (account *Account) Create() map[string]interface{} {
if resp, ok := account.Validate(); !ok {
return resp
}
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(account.Password), bcrypt.DefaultCost)
account.Password = string(hashedPassword)
account.TokenVersion = 0
GetDB().Create(account)
if account.ID <= 0 {
return u.Message(false, "Failed to create account, connection error.")
}
//Create new JWT token for the newly registered account
tk := &Token{UserId: account.ID, TokenVersion: account.TokenVersion}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
account.Password = "" //delete password
response := u.Message(true, "Account has been created")
response["token"] = tokenString
return response
}
func (account *Account) UpdateAccount() map[string]interface{} {
retAcc := &Account{}
err := db.First(&retAcc, account.ID).Error
if err != nil /*|| playlist.UserId != user*/ {
return u.Message(false, "Invalid account")
}
if account.Picture != "" {
retAcc.Picture = account.Picture
}
db.Save(&retAcc)
return u.Message(true, "Account successfully updated")
}
func (account *Account) DeleteAccount(user uint) map[string]interface{} {
retAccount := &Account{}
err := db.Table("accounts").Where("id = ?", user).First(&retAccount).Error
// should not be possible since user is fetch from auth token
if err != nil {
return u.Message(false, "This account does not exist")
}
playlists := make([]*Playlist, 0)
db.Model(retAccount).Association("FollowedPlaylists").Find(&playlists)
for _, playlist := range playlists {
db.Model(playlist).UpdateColumn("follower_count", gorm.Expr("follower_count - ?", 1))
}
db.Model(retAccount).Association("FollowedPlaylists").Clear()
db.Model(retAccount).Association("Acl").Clear()
db.Delete(&retAccount)
return u.Message(true, "Account successfully deleted")
}
func Login(email, password string) map[string]interface{} {
account := &Account{}
err := GetDB().Table("accounts").Where("email = ?", email).First(account).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return u.Message(false, "Email address not found")
}
return u.Message(false, "Connection error. Please retry")
}
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(password))
if err != nil && err == bcrypt.ErrMismatchedHashAndPassword { //Password does not match!
return u.Message(false, "Invalid login credentials. Please try again")
}
//Worked! Logged In
account.Password = ""
//Create JWT token
tk := &Token{UserId: account.ID, TokenVersion: account.TokenVersion}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
resp := u.Message(true, "Logged In")
resp["token"] = tokenString
return resp
}
func GetUser(u uint) *Account {
acc := &Account{}
GetDB().Table("accounts").Where("id = ?", u).First(acc)
if acc.Email == "" { //User not found!
return nil
}
acc.Password = ""
return acc
}
func UpdatePassword(user uint, password string) map[string]interface{} {
account := &Account{}
db.First(account, user)
resp, passed := account.ValidatePassword()
if !passed {
return resp
}
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
account.Password = string(hashedPassword)
//Create new JWT token for the newly registered account
account.TokenVersion++
tk := &Token{UserId: account.ID, TokenVersion: account.TokenVersion}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
tokenString, _ := token.SignedString([]byte(os.Getenv("token_password")))
db.Save(account)
ret := u.Message(true, "Password successfully updated")
ret["token"] = tokenString
return ret
}