package login import ( "context" "fmt" "log" "net/http" "encoding/json" "golang.org/x/oauth2" ) const ( clientID = "917c8add-f637-4773-bfde-65be8719befd" clientSecret = "eNm8Q~.LdnzWV0Px-lBHoF1YgPiL467P15a8baae" ) var ( oauthConfig *oauth2.Config ) type userInfo struct { Email string `json:"mail"` Name string `json:"displayName"` } func mInit() { oauthConfig = &oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, Endpoint: oauth2.Endpoint{ AuthURL: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token", }, RedirectURL: "http://localhost:5001/v0/auth/callback", Scopes: []string{"openid profile"}, } //http.HandleFunc("/", handleMain) //http.HandleFunc("/login", handleLogin) //http.HandleFunc("/callback", handleCallback) log.Println("Server started on http://localhost:5001") //log.Fatal(http.ListenAndServe(":8080", nil)) } func handleMain(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome to the website!") } func HandleLogin(w http.ResponseWriter, r *http.Request) string { mInit() url := oauthConfig.AuthCodeURL("state") return url } func HandleCallback(w http.ResponseWriter, r *http.Request) { code := r.URL.Query().Get("code") token, err := oauthConfig.Exchange(context.Background(), code) if err != nil { http.Error(w, fmt.Sprintf("Failed to exchange token: %v", err), http.StatusInternalServerError) return } client := oauthConfig.Client(context.Background(), token) user, err := fetchUserInfo(client) if err != nil { http.Error(w, fmt.Sprintf("Failed to fetch user info: %v", err), http.StatusInternalServerError) return } // Access the user's email and name email := user.Email name := user.Name fmt.Fprintf(w, "Authentication successful! Email: %s, Name: %s", email, name) } func fetchUserInfo(client *http.Client) (*userInfo, error) { resp, err := client.Get("https://graph.microsoft.com/v1.0/me") if err != nil { return nil, fmt.Errorf("failed to make request to Microsoft Graph API: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Microsoft Graph API returned non-OK status: %s", resp.Status) } var user userInfo if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { return nil, fmt.Errorf("failed to decode response body: %v", err) } return &user, nil }