User Logout

This example shows how you can implement user logout on the server side using the DID Token.

The example assumes:

  • You have already configured your client-side app with the Magic Client SDK
  • We are using Google AppEngine for an example below.
important

It is important to always validate the DID Token before using.

package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/magiclabs/magic-admin-go"
"github.com/magiclabs/magic-admin-go/client"
"github.com/magiclabs/magic-admin-go/token"
)
const authBearer = "Bearer"
func main() {
http.HandleFunc("/v1/user/logout", handler)
port := os.Getenv("PORT")
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.Header.Get("Authorization"), authBearer) {
fmt.Fprintf(w, "Bearer token is required")
return
}
did := r.Header.Get("Authorization")[len(authBearer)+1:]
if did == "" {
fmt.Fprintf(w, "DID token is required")
return
}
tk, err := token.NewToken(did)
if err != nil {
fmt.Fprintf(w, "Malformed DID token error: %s", err.Error())
return
}
if err := tk.Validate(); err != nil {
fmt.Fprintf(w, "DID token failed validation: %s", err.Error())
return
}
userEmail := r.URL.Query().Get("email")
// Call your appilication logic to load the user.
userInfo = logic.User.LoadByEmail(userEmail)
if userInfo.Issuer != tk.GetIssuer() {
fmt.Fprintf(w, "Unauthorized user login")
return
}
m := client.New("<YOUR_API_SECRET_KEY>", magic.NewDefaultClient())
err := m.User.LogoutByIssuer(tk.GetIssuer())
if err != nil {
fmt.Fprintf(w, "Error: %s", err.Error())
return
}
// Return a successful logout for your application.
}