Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package models
- import (
- "crypto/md5"
- "crypto/sha256"
- "errors"
- "net"
- "net/http"
- "strings"
- "github.com/google/uuid"
- )
- type User struct {
- ID uint `json:"id" gorm:"primarykey"`
- Username string `json:"username" gorm:"unique"`
- Realname string `json:"realname"`
- Password string `json:"password"`
- Ip string `json:"ip"`
- Lastlogin int64 `json:"lastlogin"`
- Regdate int64 `json:"regdate"`
- Regip string `json:"regip"`
- Email string `json:"email"`
- IsLogged bool `json:"isLogged" gorm:"column:isLogged"`
- HasSession bool `json:"hasSession" gorm:"column:hasSession"`
- Coin int64 `json:"coin"`
- UUID string `json:"uuid" gorm:"column:UUID"`
- }
- type Skin struct {
- Nick string `json:"Nick" gorm:"unique"`
- Value string `json:"Value"`
- Signature string `json:"Signature"`
- Timestamp int64 `json:"timestamp"`
- }
- func (User) TableName() string {
- return "authme"
- }
- func (Skin) TableName() string {
- return "sr_Skins"
- }
- func (user *User) HashPassword(password string) error {
- hasher := sha256.New()
- hasher.Write([]byte(password))
- user.Password = string(hasher.Sum(nil))
- return nil
- }
- func (user *User) CheckPassword(providedPassword string) error {
- hasher := sha256.New()
- hasher.Write([]byte(providedPassword))
- providedHashedPassword := string(hasher.Sum(nil))
- if user.Password != providedHashedPassword {
- return errors.New("invalid password")
- }
- return nil
- }
- func (user *User) NameToUUID() error {
- if user.Realname == "" {
- return errors.New("realname not set")
- }
- var version = 3
- h := md5.New()
- h.Write([]byte("OfflinePlayer:"))
- h.Write([]byte(user.Realname))
- var id uuid.UUID
- h.Sum(id[:0])
- id[6] = (id[6] & 0x0f) | uint8((version&0xf)<<4)
- id[8] = (id[8] & 0x3f) | 0x80 // RFC 4122 variant
- user.UUID = id.String()
- return nil
- }
- func (user *User) SetIP(r *http.Request) error {
- //Get IP from the X-REAL-IP header
- ip := r.Header.Get("X-REAL-IP")
- netIP := net.ParseIP(ip)
- if netIP != nil {
- user.Ip = ip
- user.Regip = ip
- return nil
- }
- //Get IP from X-FORWARDED-FOR header
- ips := r.Header.Get("X-FORWARDED-FOR")
- splitIps := strings.Split(ips, ",")
- for _, ip := range splitIps {
- netIP := net.ParseIP(ip)
- if netIP != nil {
- user.Ip = ip
- user.Regip = ip
- return nil
- }
- }
- //Get IP from RemoteAddr
- ip, _, err := net.SplitHostPort(r.RemoteAddr)
- if err != nil {
- return err
- }
- netIP = net.ParseIP(ip)
- if netIP != nil {
- user.Ip = ip
- user.Regip = ip
- return nil
- }
- return errors.New("no valid ip found")
- }
Advertisement
Add Comment
Please, Sign In to add comment