Advertisement
Guest User

main.go

a guest
Mar 12th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 8.23 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     "github.com/dgrijalva/jwt-go"
  7.     "github.com/gorilla/mux"
  8.     "io"
  9.     "io/ioutil"
  10.     "log"
  11.     "net/http"
  12.     "os"
  13.     "os/exec"
  14.     "sort"
  15.     "strconv"
  16. )
  17.  
  18. // ToDo бахнуть обработку ошибок
  19.  
  20. type User struct {
  21.     ID       string
  22.     Nickname string `json:"nickname"`
  23.     Email    string `json:"email"`
  24.     Password string `json:"password"`
  25.     Points   int
  26.     Age      int
  27.     ImgUrl   string
  28.     Region   string
  29.     About    string
  30. }
  31.  
  32. type Order struct {
  33.     Sequence string `json:"order"`
  34. }
  35.  
  36. //ToDo: Move to another package
  37. var errorLogin = map[string]string{
  38.     "Error": "User dont exist",
  39. }
  40.  
  41. var errorCreateUser = map[string]string{
  42.     "Error": "Nickname/mail already exists",
  43. }
  44.  
  45. var users []User
  46.  
  47. func (u *User) setUniqueId() {
  48.     // DB incremental or smth
  49.     out, _ := exec.Command("uuidgen").Output()
  50.     u.Points = 0
  51.     u.ID = string(out[:len(out)-1])
  52. }
  53.  
  54. func createUser(w http.ResponseWriter, r *http.Request) {
  55.     fmt.Println(users)
  56.     w.Header().Set("Content-Type", "application/json")
  57.     var newUser User
  58.     _ = json.NewDecoder(r.Body).Decode(&newUser) // ToDo: Log error
  59.     for _, existUser := range users {
  60.         if newUser.Nickname == existUser.Nickname || newUser.Email == existUser.Email {
  61.             json.NewEncoder(w).Encode(errorCreateUser)
  62.             return
  63.         }
  64.     }
  65.     newUser.setUniqueId()
  66.     users = append(users, newUser) // Check succesfull append? ( in db clearly )
  67.     //json.NewEncoder(w).Encode(newUser)
  68.  
  69. }
  70.  
  71. //ToDo: Use get with key order? (ASC/DESC )
  72. //ToDo: Check and simplify conditions !!!
  73. func getLeaderboard(w http.ResponseWriter, r *http.Request) {
  74.     w.Header().Set("Content-Type", "application/json")
  75.     var order Order
  76.     var pageSize int
  77.     // Initilize pagesize
  78.     pageSize = 1
  79.     _ = json.NewDecoder(r.Body).Decode(&order)
  80.     sort.Slice(users, func(i, j int) bool {
  81.         return users[i].Points > users[j].Points
  82.     })
  83.     offset, getOffset := r.URL.Query()["offset"]
  84.     if getOffset {
  85.         offsetInt, _ := strconv.ParseInt(offset[0], 10, 32) // ToDo Handle error
  86.         if int(offsetInt) > len(users) {
  87.             json.NewEncoder(w).Encode(users)
  88.             return
  89.         } else if int(offsetInt) == len(users) {
  90.             json.NewEncoder(w).Encode(users)
  91.             return
  92.         }
  93.         if int(offsetInt)+pageSize < len(users) {
  94.             json.NewEncoder(w).Encode(users[offsetInt : int(offsetInt)+pageSize])
  95.             return
  96.         } else {
  97.             json.NewEncoder(w).Encode(users[offsetInt:len(users)])
  98.             return
  99.         }
  100.     } else {
  101.         if pageSize < len(users) {
  102.             json.NewEncoder(w).Encode(users[:pageSize])
  103.             return
  104.         } else {
  105.             json.NewEncoder(w).Encode(users)
  106.             return
  107.         }
  108.     }
  109.  
  110. }
  111.  
  112. func createSessionId(user User) string {
  113.     token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  114.         "id": user.ID,
  115.     })
  116.     // ToDo: Error handle
  117.     spiceSalt, _ := ioutil.ReadFile("secret.conf")
  118.     secretStr, _ := token.SignedString(spiceSalt)
  119.     return secretStr
  120. }
  121.  
  122. func checkAuth(cookie *http.Cookie) jwt.MapClaims {
  123.     token, _ := jwt.Parse(cookie.Value, func(token *jwt.Token) (interface{}, error) {
  124.         if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  125.             return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  126.         }
  127.         spiceSalt, _ := ioutil.ReadFile("secret.conf")
  128.         return spiceSalt, nil
  129.     })
  130.  
  131.     claims, _ := token.Claims.(jwt.MapClaims)
  132.  
  133.     // ToDo: Handle else case
  134.     return claims
  135. }
  136.  
  137. func isAuth(w http.ResponseWriter, r *http.Request) {
  138.     cookie, err := r.Cookie("session_id")
  139.     if err != nil {
  140.         fmt.Println(r.Cookie("session_id"),err)
  141.         w.Write([]byte("{}"))
  142.         return
  143.     }
  144.  
  145.     claims := checkAuth(cookie)
  146.     fmt.Println(claims)
  147.     for _, user := range users {
  148.         if user.ID == claims["id"] {
  149.             json.NewEncoder(w).Encode(map[string]bool{"is_auth": true})
  150.             fmt.Println("True");
  151.             return
  152.         }
  153.     }
  154.     fmt.Println("False");
  155.     json.NewEncoder(w).Encode(map[string]bool{"is_auth": false})
  156. }
  157.  
  158. func editUser(w http.ResponseWriter, r *http.Request) {
  159.     fmt.Println(users)
  160.     //Checking cookie
  161.     cookie, err := r.Cookie("session_id")
  162.     if err != nil {
  163.         w.Write([]byte("{}"))
  164.         return
  165.     }
  166.     // Taking JSON of modified user from edit form
  167.     var modUser User
  168.     _ = json.NewDecoder(r.Body).Decode(&modUser)
  169.     file, _, err := r.FormFile("avatar")
  170.     fmt.Println(file)
  171.     // Getting claims from current cookie
  172.     claims := checkAuth(cookie)
  173.  
  174.     // Finding user from claims in users and changing old data to modified data
  175.     for i, user := range users {
  176.         if user.ID == claims["id"].(string) {
  177.             u := &users[i]
  178.             if modUser.Nickname != "" {
  179.                 u.Nickname = modUser.Nickname
  180.             }
  181.             if modUser.Email != "" {
  182.                 u.Email = modUser.Email
  183.             }
  184.             if modUser.Password != "" {
  185.                 u.Password = modUser.Password
  186.             }
  187.             if modUser.Region != "" {
  188.                 u.Region = modUser.Region
  189.             }
  190.             if modUser.Age != 0 {
  191.                 u.Age = modUser.Age
  192.             }
  193.             if modUser.About != "" {
  194.                 u.About = modUser.About
  195.             }
  196.             if modUser.ImgUrl != "" {
  197.                 u.ImgUrl = modUser.ImgUrl
  198.             }
  199.             json.NewEncoder(w).Encode(*u)
  200.             break
  201.         }
  202.     }
  203. }
  204.  
  205. func login(w http.ResponseWriter, r *http.Request) {
  206.     var sessionId string
  207.     var userExistFlag bool
  208.     var existUser User
  209.     _ = json.NewDecoder(r.Body).Decode(&existUser)
  210.     for _, user := range users {
  211.         if user.Nickname == existUser.Nickname && user.Password == existUser.Password {
  212.             userExistFlag = true
  213.             existUser = user
  214.         }
  215.     }
  216.     if !userExistFlag {
  217.         json.NewEncoder(w).Encode(errorLogin)
  218.         return
  219.     }
  220.     sessionId = createSessionId(existUser)
  221.     cookie := &http.Cookie{
  222.         Name:     "session_id",
  223.         Value:    sessionId,
  224.         HttpOnly: false,
  225.     }
  226.     http.SetCookie(w, cookie)
  227.     json.NewEncoder(w).Encode(existUser)
  228. }
  229.  
  230. func getMe(w http.ResponseWriter, r *http.Request) {
  231.     cookie, err := r.Cookie("session_id")
  232.     if err != nil {
  233.         w.Write([]byte("{}"))
  234.         return
  235.     }
  236.     claims := checkAuth(cookie)
  237.     for _, user := range users {
  238.         if user.ID == claims["id"].(string) {
  239.             json.NewEncoder(w).Encode(user)
  240.             return
  241.         }
  242.     }
  243. }
  244.  
  245. // ToDO: Add case sensitive ( high/low )
  246. func getUser(w http.ResponseWriter, r *http.Request) {
  247.  
  248.     w.Header().Set("Content-Type", "application/json")
  249.     params := mux.Vars(r)
  250.     for _, item := range users {
  251.         //id, _ := strconv.Atoi(params["ID"])
  252.         if item.ID == params["id"] {
  253.             json.NewEncoder(w).Encode(item)
  254.             return
  255.         }
  256.     }
  257.     json.NewEncoder(w).Encode(&User{})
  258. }
  259.  
  260. func upload(w http.ResponseWriter, r *http.Request) {
  261.     // Tacking file from request
  262.     fmt.Println("UPLOAD")
  263.     r.ParseMultipartForm(32 << 20)
  264.     fmt.Println(r)
  265.     file, _, err := r.FormFile("uploadfile")
  266.     if err != nil {
  267.         fmt.Println(err)
  268.         return
  269.     }
  270.     defer file.Close()
  271.     fmt.Println("FILE IS HERE")
  272.  
  273.     // Tacking cookie of current user
  274.     cookie, err := r.Cookie("session_id")
  275.     if err != nil {
  276.         w.Write([]byte("{}"))
  277.         return
  278.     }
  279.     claims := checkAuth(cookie)
  280.     // Path to users avatar
  281.     picpath := "./static/img/" + claims["id"].(string) + ".jpeg"
  282.     f, err := os.OpenFile(picpath, os.O_WRONLY|os.O_CREATE, 0666)
  283.     if err != nil {
  284.         fmt.Println(err)
  285.         return
  286.     }
  287.  
  288.     // Changing ImgURL field in current user
  289.     for i, user := range users {
  290.         if user.ID == claims["id"].(string) {
  291.             u := &users[i]
  292.             u.ImgUrl = picpath
  293.         }
  294.     }
  295.     defer f.Close()
  296.     io.Copy(f, file)
  297. }
  298.  
  299. func main() {
  300.     // Mocked part for leaderboard
  301.     var mockedUser = User{"1", "evv", "onetaker@gmail.com",
  302.         "evv", -100, 23, "test",
  303.         "Voronezh", "В левой руке салам"}
  304.     var mockedUser1 = User{"2", "tony", "trendpusher@hydra.com",
  305.         "qwerty", 100, 22, "test",
  306.         "Moscow", "В правой алейкум"}
  307.     // Mocker part end
  308.     users = append(users, mockedUser)
  309.     users = append(users, mockedUser1)
  310.     reciever := mux.NewRouter()
  311.     // GET  ( get exists data )
  312.  
  313.     reciever.HandleFunc("/users/{Nickname}", getUser).Methods("GET")
  314.  
  315.     reciever.HandleFunc("/leaderboard", getLeaderboard).Methods("GET")
  316.     reciever.HandleFunc("/isauth", isAuth).Methods("GET")
  317.     reciever.HandleFunc("/me", getMe).Methods("Get")
  318.     //reciever.HandleFunc("/edit", editUser).Methods("GET")
  319.  
  320.     // POST ( create new data )
  321.     reciever.HandleFunc("/signup", createUser).Methods("POST")
  322.     reciever.HandleFunc("/upload", upload).Methods("POST")
  323.     reciever.HandleFunc("/login", login).Methods("POST")
  324.     reciever.HandleFunc("/users/{Nickname}", editUser).Methods("POST")
  325.  
  326.     reciever.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/"))) // Uncomment if want to run locally
  327.     log.Fatal(http.ListenAndServe(":8080", reciever))
  328. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement