81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
|
||
|
"github.com/globalsign/mgo/bson"
|
||
|
)
|
||
|
|
||
|
//User model
|
||
|
type User struct {
|
||
|
ID bson.ObjectId `bson:"_id,omitempty"`
|
||
|
Email string `bson:"email"`
|
||
|
Name string `bson:"name"`
|
||
|
Username string `bson:"username"`
|
||
|
Password string `bson:"password"`
|
||
|
PrimaryGroup bson.ObjectId `bson:"primarygroup,omitempty"`
|
||
|
Groups []bson.ObjectId `bson:"groups,omitempty"`
|
||
|
Session string
|
||
|
}
|
||
|
|
||
|
//Create user
|
||
|
func (u *User) Create() error {
|
||
|
var user User
|
||
|
read("user", "email", u.Email, &user)
|
||
|
if u.Email == user.Email {
|
||
|
return errors.New("Email all ready used")
|
||
|
}
|
||
|
return create("user", &u)
|
||
|
|
||
|
}
|
||
|
|
||
|
//Read user
|
||
|
func (u *User) Read(key string, value interface{}) error {
|
||
|
err := read("user", key, value, &u)
|
||
|
if err != nil {
|
||
|
return errors.New("User doesn't exist")
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
//ReadAll users
|
||
|
func (u *User) ReadAll() ([]User, error) {
|
||
|
var users []User
|
||
|
var err error
|
||
|
err = readAll("user", "", nil, &users)
|
||
|
return users, err
|
||
|
|
||
|
}
|
||
|
|
||
|
//Update user
|
||
|
func (u *User) Update() error {
|
||
|
return update("user", "_id", u.ID, &u)
|
||
|
}
|
||
|
|
||
|
//Delete user
|
||
|
func (u *User) Delete(key string, value string) error {
|
||
|
err := delete("user", key, value)
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
//HasPermission check if a given user is admin or has a given permisssion
|
||
|
func (u *User) HasPermission(perm string) bool {
|
||
|
var group Group
|
||
|
//Check primary group
|
||
|
err := group.Read("_id", u.PrimaryGroup)
|
||
|
fmt.Println(group.Admin)
|
||
|
if err == nil && (group.Admin == true || group.Permissions[perm] == true) {
|
||
|
|
||
|
return true
|
||
|
}
|
||
|
//Check other groups
|
||
|
for id := range u.Groups {
|
||
|
err = group.Read("_id", id)
|
||
|
if err == nil && (group.Admin || group.Permissions[perm]) {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|