-
Notifications
You must be signed in to change notification settings - Fork 20
/
models.go
74 lines (62 loc) · 1.58 KB
/
models.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
package app
import (
"crypto/sha1"
"fmt"
"github.com/jmoiron/monet/db"
"io"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"regexp"
"strings"
)
// -- Standard Models --
type User struct {
Id bson.ObjectId "_id"
Username string
Password string
}
func (u *User) Indexes() [][]string { return [][]string{[]string{"username"}} }
func (u *User) Collection() string { return "users" }
func (u *User) Unique() bson.M { return bson.M{"username": u.Username} }
func (u *User) PreSave() {}
// -- Users --
func CreateUser(username, password string) error {
hash := sha1.New()
io.WriteString(hash, password)
user := new(User)
user.Username = username
user.Password = fmt.Sprintf("%x", hash.Sum(nil))
_, err := db.Upsert(user)
return err
}
func ValidateUser(username, password string) bool {
hash := sha1.New()
io.WriteString(hash, password)
user := new(User)
hashstr := fmt.Sprintf("%x", hash.Sum(nil))
err := db.Find(user, bson.M{"username": username}).One(&user)
if err == mgo.ErrNotFound {
return false
}
if user.Password != hashstr {
return false
}
return true
}
// -- Utilities --
var (
stripspace = regexp.MustCompile("[^\\w\\s\\-]")
dashreplace = regexp.MustCompile("[^\\w]+")
)
// Slugify some text. Do not strip words as django does, but do collapse
// spaces and use dashes in favor of all other non-alphanum characters.
func Slugify(text string) string {
s := text
s = stripspace.ReplaceAllString(s, "")
s = dashreplace.ReplaceAllString(s, "-")
s = strings.Replace(s, "_", "-", -1)
return strings.ToLower(s)
}
func init() {
db.Register(&User{})
}