github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/api/user.go (about)

     1  // Copyright 2020 The WPT Dashboard Project. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file
     4  
     5  package api
     6  
     7  import (
     8  	"encoding/json"
     9  	"net/http"
    10  
    11  	"github.com/web-platform-tests/wpt.fyi/shared"
    12  )
    13  
    14  type loginSuccessResponse struct {
    15  	User *shared.User `json:"user"`
    16  }
    17  
    18  type loginFailureResponse struct {
    19  	Error string `json:"error"`
    20  }
    21  
    22  func apiUserHandler(w http.ResponseWriter, r *http.Request) {
    23  	ctx := r.Context()
    24  	aeAPI := shared.NewAppEngineAPI(ctx)
    25  	if !aeAPI.IsFeatureEnabled("githubLogin") {
    26  		http.Error(w, "Feature not enabled", http.StatusNotImplemented)
    27  
    28  		return
    29  	}
    30  
    31  	ds := shared.NewAppEngineDatastore(ctx, false)
    32  	user, _ := shared.GetUserFromCookie(ctx, ds, r)
    33  	if user == nil {
    34  		response := loginFailureResponse{Error: "Unable to retrieve login information, please log in again"}
    35  		marshalled, err := json.Marshal(response)
    36  		if err != nil {
    37  			http.Error(w, err.Error(), http.StatusInternalServerError)
    38  
    39  			return
    40  		}
    41  
    42  		w.WriteHeader(http.StatusUnauthorized)
    43  		_, err = w.Write(marshalled)
    44  		if err != nil {
    45  			logger := shared.GetLogger(ctx)
    46  			logger.Warningf("Failed to write data in api/user handler: %s", err.Error())
    47  		}
    48  
    49  		return
    50  	}
    51  
    52  	response := loginSuccessResponse{User: user}
    53  	marshalled, err := json.Marshal(response)
    54  	if err != nil {
    55  		http.Error(w, err.Error(), http.StatusInternalServerError)
    56  
    57  		return
    58  	}
    59  
    60  	_, err = w.Write(marshalled)
    61  	if err != nil {
    62  		logger := shared.GetLogger(ctx)
    63  		logger.Warningf("Failed to write data in api/user handler: %s", err.Error())
    64  	}
    65  }