Created
February 6, 2022 10:51
-
-
Save muhammadqazi/8a395816e3f3fcaa974fb099c8036c8e to your computer and use it in GitHub Desktop.
Go-Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func HandleSignin(response http.ResponseWriter, request *http.Request) { | |
if request.Method != "POST" { | |
response.WriteHeader(http.StatusMethodNotAllowed) | |
response.Write([]byte("{\"message\": \"Method not allowed\"}")) | |
return | |
} | |
var user model.AuthenticationModel | |
var result model.ResponseModel | |
dec := json.NewDecoder(request.Body) | |
dec.DisallowUnknownFields() | |
err := dec.Decode(&user) | |
if err != nil { | |
http.Error(response, err.Error(), http.StatusBadRequest) | |
if errors.Is(err, io.EOF) { | |
response.WriteHeader(http.StatusBadRequest) | |
response.Write([]byte("{\"message\": \"UnAthorized\"}")) | |
} | |
return | |
} | |
auth, email, fname, lname, userid := database.HandleAuthentication(user.Email, user.Password, "GO", "users") | |
token, _, _ := helper.JWTTokenGenerator(email, fname, lname, userid) | |
result.Token = token | |
result.Expires_in = time.Now().Local().Add(time.Hour * time.Duration(24)).Unix() | |
if !auth { | |
response.WriteHeader(http.StatusUnauthorized) | |
response.Write([]byte("{\"message\": \"Invalid Credentials\"}")) | |
return | |
} else if auth { | |
response.WriteHeader(http.StatusOK) | |
json.NewEncoder(response).Encode(&result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment