Advertisement
Guest User

pasin_paste

a guest
Jul 30th, 2014
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.49 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4. import "net/http"
  5. import "encoding/json"
  6. import "code.google.com/p/go.crypto/bcrypt"
  7.  
  8. const LEN_PASSWORD = 8
  9.  
  10. type Password struct {
  11.     Hash  string `json:"hash"`
  12.     Plain string `json:"plain"`
  13. }
  14.  
  15. func main() {
  16.  
  17.     http.HandleFunc("/compare",
  18.         func(res http.ResponseWriter, req *http.Request) {
  19.             var comparison Password
  20.  
  21.             err := json.NewDecoder(req.Body).Decode(&comparison)
  22.  
  23.             if err != nil {
  24.                 http.Error(res, err.Error(), http.StatusBadRequest)
  25.                 return
  26.             }
  27.         })
  28.  
  29.     http.HandleFunc("/hash",
  30.         func(res http.ResponseWriter, req *http.Request) {
  31.             var hashable Password
  32.  
  33.             err := json.NewDecoder(req.Body).Decode(&hashable)
  34.  
  35.             if err != nil {
  36.                 http.Error(res, err.Error(), http.StatusBadRequest)
  37.                 return
  38.             }
  39.  
  40.             if len(hashable.Plain) < LEN_PASSWORD {
  41.                 http.Error(res,
  42.                     fmt.Sprintf(
  43.                         "Password must be at least %d characters!",
  44.                         LEN_PASSWORD),
  45.                     http.StatusBadRequest)
  46.                 return
  47.             }
  48.  
  49.             hash, err := bcrypt.GenerateFromPassword(
  50.                 []byte(hashable.Plain),
  51.                 bcrypt.DefaultCost)
  52.  
  53.             if err != nil {
  54.                 http.Error(res, err.Error(), http.StatusInternalServerError)
  55.                 return
  56.             }
  57.  
  58.             hashable.Hash = string(hash)
  59.             jsonData, err := json.Marshal(hashable)
  60.  
  61.             if err != nil {
  62.                 http.Error(res, err.Error(), http.StatusInternalServerError)
  63.                 return
  64.             }
  65.  
  66.             res.Write(jsonData)
  67.         })
  68.  
  69.     err := http.ListenAndServe(":3000", nil)
  70.  
  71.     if err != nil {
  72.         fmt.Println("voi vittu", err)
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement