siga

Sistema Interativo de GerĂȘncia de Atividades.
Log | Files | Refs | README | LICENSE

authenticated.go (891B)


      1 package main
      2 
      3 import (
      4 	"database/sql"
      5 	"encoding/json"
      6 	"errors"
      7 	"log"
      8 	"net/http"
      9 	"uuid"
     10 
     11 	"github.com/gboncoffee/siga/auth/repository"
     12 )
     13 
     14 type AuthenticatedResponse struct {
     15 	Username string
     16 }
     17 
     18 // GET /{uuid} answers whether the session exists and, if so, whose it is.
     19 func authenticated(w http.ResponseWriter, r *http.Request) {
     20 	token, err := uuid.Parse(r.PathValue("uuid"))
     21 	if err != nil {
     22 		http.Error(w, "invalid token", http.StatusBadRequest)
     23 		return
     24 	}
     25 
     26 	username, err := repository.SessionUsername(token)
     27 	if errors.Is(err, sql.ErrNoRows) {
     28 		http.Error(w, "invalid token", http.StatusUnauthorized)
     29 		return
     30 	}
     31 	if err != nil {
     32 		log.Println("session lookup:", err)
     33 		http.Error(w, "internal server error", http.StatusInternalServerError)
     34 		return
     35 	}
     36 
     37 	w.Header().Set("Content-Type", "application/json")
     38 	json.NewEncoder(w).Encode(AuthenticatedResponse{Username: username})
     39 }