Library/models/user.go

59 lines
1.4 KiB
Go
Raw Normal View History

package models
import (
"fmt"
2017-11-07 15:35:10 +00:00
"golang.org/x/crypto/bcrypt"
)
2017-11-08 16:12:05 +00:00
// UserLogin Object to recive user credentials in JSON format
type UserLogin struct {
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
}
2017-11-08 09:55:17 +00:00
// User holds information about an user
type User struct {
2017-11-07 15:35:10 +00:00
ID int64 `xorm:"int(11) autoincr not null unique pk"`
Name string `xorm:"varchar(250)"`
Username string `xorm:"varchar(250) not null"`
Password string `xorm:"varchar(250) not null"`
2017-11-07 15:35:10 +00:00
Email string `xorm:"varchar(250) not null"`
Created int64 `xorm:"created"`
Updated int64 `xorm:"updated"`
}
2017-11-08 09:55:17 +00:00
// TableName returns the table name for users
func (User) TableName() string {
return "users"
}
2017-11-08 09:55:17 +00:00
// HashPassword hashes a password
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
2017-11-08 09:55:17 +00:00
// CheckUserCredentials checks user credentials
2017-11-08 16:12:05 +00:00
func CheckUserCredentials(u UserLogin) (User, error) {
// Check if the user exists
var user = User{Username: u.Username}
exists, err := x.Get(&user)
if err != nil {
return User{}, err
}
if !exists {
2017-11-08 09:55:17 +00:00
return User{}, fmt.Errorf("user does not exist")
}
// Check the users password
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password))
if err != nil {
return User{}, err
}
return user, nil
2017-11-07 15:35:10 +00:00
}