GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.3 KiB

  1. package auth
  2. import (
  3. "git.aiterp.net/rpdata/api/internal/store"
  4. "github.com/globalsign/mgo"
  5. )
  6. var userCollection *mgo.Collection
  7. // A User represents user information about a user that has logged in.
  8. type User struct {
  9. ID string `bson:"_id" json:"id"`
  10. Nick string `bson:"nick,omitempty" json:"nick,omitempty"`
  11. Permissions []string `bson:"permissions" json:"permissions"`
  12. }
  13. // Permitted returns true if either of the permissions can be found
  14. //
  15. // `token.UserID == page.Author || token.Permitted("story.edit")`
  16. func (user *User) Permitted(permissions ...string) bool {
  17. for i := range permissions {
  18. for j := range user.Permissions {
  19. if permissions[i] == user.Permissions[j] {
  20. return true
  21. }
  22. }
  23. }
  24. return false
  25. }
  26. // FindUser finds a user by userid
  27. func FindUser(userid string) (User, error) {
  28. user := User{}
  29. err := userCollection.FindId(userid).One(&user)
  30. if err == mgo.ErrNotFound {
  31. user := User{
  32. ID: userid,
  33. Nick: "",
  34. Permissions: []string{
  35. "member",
  36. "log.edit",
  37. "post.edit",
  38. "post.move",
  39. "file.upload",
  40. },
  41. }
  42. err := userCollection.Insert(user)
  43. if err != nil {
  44. return User{}, err
  45. }
  46. }
  47. return user, err
  48. }
  49. func init() {
  50. store.HandleInit(func(db *mgo.Database) {
  51. userCollection = db.C("core.users")
  52. })
  53. }