// Login login user func (c AuthController) Login(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { model := &models.LoginModel{} if err := json.NewDecoder(r.Body).Decode(model); err != nil { c.Logger.Log("AuthController login json decode.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 1}) return } conn := factory.NewDatabase().Connection() if err := conn.Open(); err != nil { c.Logger.Log("AuthController login could not open db connection.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 2}) return } defer conn.Close() user, err := factory.NewDatabase().User(conn).FindByEmail(model.Email) if err != nil || user == nil { c.Logger.Log("AuthController login find by email.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 3}) return } if user.Email != strings.ToLower(model.Email) || user.Password != model.Password { c.Logger.Log("AuthController login invalid username or password.", nil) json.NewEncoder(w).Encode(models.Response{ErrorCode: 4}) return } json.NewEncoder(w).Encode(models.Response{Data: user, Success: true}) }
// ServeHTTP handles web requests func (s LocationSocket) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { s.logger.Log("websocket connection open error:", err) } defer conn.Close() conn.SetReadLimit(maxMessageSize) conn.SetReadDeadline(time.Now().Add(pongWait)) conn.SetPongHandler(func(string) error { conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) id := mux.Vars(r)["id"] if id == "" || !bson.IsObjectIdHex(id) { conn.Close() s.logger.Log("LocationSocket ServeHTTP id is not a bson id.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 5}) return } dbConn := factory.NewDatabase().Connection() if err := dbConn.Open(); err != nil { s.logger.Log("LocationSocket ServeHTTP could not open db connection.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 2}) return } defer dbConn.Close() user, err := factory.NewDatabase().User(dbConn).FindByID(bson.ObjectIdHex(id)) if err != nil || user == nil { s.logger.Log("LocationSocket ServeHTTP find by id.", err) json.NewEncoder(w).Encode(models.Response{ErrorCode: 3}) return } s.addConnection(LocationInfo{ID: id, Name: user.Name, IconImage: user.Image.Icon, ThumbImage: user.Image.Thumb}, conn) for { model := models.GeoLocationModel{} if err := websocket.ReadJSON(conn, &model); err != nil { s.logger.Log("Conn read message error:", err) s.disconnect(conn) return } s.sendLocationMessage(model, s.connections[conn]) } }