am-i-alive-go

Make it easy for people to check if you are alive or not.
git clone http://git.hanabi.in/repos/am-i-alive-go.git
Log | Files | Refs | README | LICENSE

update-last-active-utils.go (2226B)


      1 package handlers
      2 
      3 import (
      4 	"crypto/sha512"
      5 	"database/sql"
      6 	"encoding/hex"
      7 	"encoding/json"
      8 	"fmt"
      9 	"io"
     10 	"net/http"
     11 	"time"
     12 
     13 	"git.hanabi.in/dev/am-i-alive/config"
     14 	"git.hanabi.in/dev/am-i-alive/consts"
     15 	JsonStructs "git.hanabi.in/dev/am-i-alive/json-structs"
     16 )
     17 
     18 func getRespForUpdateLastActive(r *http.Request) (header int, resp []byte) {
     19 	is_db_updated := false
     20 	if r.Method != http.MethodPost { // if method was not POST
     21 		header = http.StatusMethodNotAllowed
     22 		err_msg := "Method not allowed."
     23 		resp, _ = json.Marshal(JsonStructs.ErrJson{Err: err_msg})
     24 	} else {
     25 		if err, res := isAuthFailed(r.Body); res == true { // if auth failed.
     26 			header = http.StatusUnauthorized
     27 			err_msg := err.Error()
     28 			resp, _ = json.Marshal(JsonStructs.AuthFailErrJson{Err: err_msg, Updated: is_db_updated})
     29 		} else {
     30 			if err := tryUpdatingDb(); err != nil { // if error occurred while updating DB.
     31 				header = http.StatusInternalServerError
     32 				err_msg := err.Error()
     33 				resp, _ = json.Marshal(JsonStructs.AuthFailErrJson{Err: err_msg, Updated: is_db_updated})
     34 			} else {
     35 				is_db_updated = true
     36 				header = http.StatusOK
     37 				resp, _ = json.Marshal(JsonStructs.AuthSuccessJson{Updated: is_db_updated})
     38 			}
     39 		}
     40 	}
     41 	return header, resp
     42 }
     43 
     44 func tryUpdatingDb() (err error) {
     45 	db, err := open_db()
     46 	defer db.Close()
     47 
     48 	if err == nil {
     49 		err = queryUpdateLastSeen(db)
     50 	}
     51 	return err
     52 }
     53 
     54 // Update DB to store updated at as (UNIX timestamp - offset)
     55 func queryUpdateLastSeen(db *sql.DB) (err error) {
     56 	now := time.Now().Unix() - consts.Offset
     57 	query_str := "UPDATE alive SET updatedat = ? WHERE id = 0"
     58 	stmt, err := db.Prepare(query_str)
     59 	_, err = stmt.Exec(now)
     60 	stmt.Close()
     61 	return err
     62 }
     63 
     64 // Check if sha512 of the auth sent in the request body is same as in the config.
     65 func isAuthFailed(body io.ReadCloser) (err error, isFailed bool) {
     66 	isFailed = true
     67 	decoder := json.NewDecoder(body)
     68 	var auth JsonStructs.AuthJson
     69 	if err = decoder.Decode(&auth); err == nil {
     70 		s := sha512.New()
     71 		s.Write([]byte(auth.Auth))
     72 		received_auth_hash := fmt.Sprint(hex.EncodeToString(s.Sum(nil)))
     73 		if config.Auth != received_auth_hash {
     74 			err = fmt.Errorf("Incorrect credentials.")
     75 		} else {
     76 			isFailed = false
     77 		}
     78 	}
     79 	return err, isFailed
     80 }