github.com/simpleiot/simpleiot@v0.18.3/api/auth.go (about) 1 package api 2 3 import ( 4 "log" 5 "net/http" 6 7 "github.com/nats-io/nats.go" 8 "github.com/simpleiot/simpleiot/client" 9 "github.com/simpleiot/simpleiot/data" 10 ) 11 12 // Auth handles user authentication requests. 13 type Auth struct { 14 nc *nats.Conn 15 } 16 17 // NewAuthHandler returns a new authentication handler using the given key. 18 func NewAuthHandler(nc *nats.Conn) Auth { 19 return Auth{nc: nc} 20 } 21 22 // ServeHTTP serves requests to authenticate. 23 func (auth Auth) ServeHTTP(res http.ResponseWriter, req *http.Request) { 24 if req.Method != http.MethodPost { 25 http.Error(res, "only POST allowed", http.StatusMethodNotAllowed) 26 return 27 } 28 29 email := req.FormValue("email") 30 password := req.FormValue("password") 31 32 nodes, err := client.UserCheck(auth.nc, email, password) 33 if err != nil { 34 http.Error(res, err.Error(), http.StatusInternalServerError) 35 return 36 } 37 38 if len(nodes) == 0 { 39 http.Error(res, "invalid login", http.StatusForbidden) 40 return 41 } 42 43 var token string 44 45 for _, n := range nodes { 46 if n.Type == data.NodeTypeJWT { 47 p, ok := n.Points.Find(data.PointTypeToken, "") 48 if ok { 49 token = p.Text 50 } 51 } 52 } 53 54 err = encode(res, data.Auth{ 55 Token: token, 56 Email: email, 57 }) 58 59 if err != nil { 60 log.Println("Error encoding:", err) 61 } 62 }