The backend for the AiteStory website
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.

96 lines
2.2 KiB

7 years ago
  1. package controllers
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "strings"
  7. "git.aiterp.net/AiteRP/aitestory/server"
  8. "git.aiterp.net/gisle/wrouter/auth"
  9. "github.com/sadbox/mediawiki"
  10. )
  11. // WikiAthenticator talks with the wiki, allowing users
  12. // to log in
  13. type WikiAthenticator struct{}
  14. func (wikiAuth *WikiAthenticator) ID() string {
  15. return "wiki"
  16. }
  17. func (wikiAuth *WikiAthenticator) Name() string {
  18. return "Wiki"
  19. }
  20. func (wikiAuth *WikiAthenticator) Find(username string) *auth.User {
  21. db := server.Main.DB
  22. rows, err := db.Query("SELECT id,role FROM `user` WHERE id=?", username)
  23. if err != nil {
  24. log.Println("WikiAthenticator.Find:", err)
  25. return nil
  26. }
  27. defer rows.Close()
  28. if !rows.Next() {
  29. return nil
  30. }
  31. user := auth.NewUser(wikiAuth, "", "member", nil)
  32. role := "member"
  33. rows.Scan(&user.ID, &role)
  34. user.Data["role"] = role
  35. return user
  36. }
  37. // Login login
  38. func (wikiAuth *WikiAthenticator) Login(username, password string) (*auth.User, error) {
  39. db := server.Main.DB
  40. // Connect to the wiki
  41. client, err := mediawiki.New(server.Main.Config.Wiki.URL, server.UserAgent)
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. // Log into the wiki with the credementials
  46. err = client.Login(username, password)
  47. if err != nil {
  48. return nil, fmt.Errorf("Login failed %v", err)
  49. }
  50. // Look up the user
  51. rows, err := db.Query("SELECT id,role FROM `user` WHERE id=?", client.BasicAuthUser)
  52. if err != nil {
  53. return nil, fmt.Errorf("Login failed %v", err)
  54. return nil, nil
  55. }
  56. // If none was found, just create a new record with the role of member
  57. if !rows.Next() {
  58. _, err = db.Exec("INSERT INTO `user` (id, role) VALUES (?, 'member')", client.BasicAuthUser)
  59. if err != nil {
  60. return nil, fmt.Errorf("Login failed %v", err)
  61. }
  62. return auth.NewUser(wikiAuth, client.BasicAuthUser, "member", nil), nil
  63. }
  64. // If the user was found, read it in
  65. userid, role := "", ""
  66. err = rows.Scan(&userid, &role)
  67. if err != nil {
  68. return nil, fmt.Errorf("Login failed %v", err)
  69. }
  70. userid = strings.Split(userid, "@")[0]
  71. // Make the user
  72. return auth.NewUser(wikiAuth, userid, "member", nil), nil
  73. }
  74. func (wikiAuth *WikiAthenticator) Register(username, password string, data map[string]string) (*auth.User, error) {
  75. return nil, errors.New("Registration not allowed")
  76. }