Last active
May 2, 2024 10:31
-
-
Save agrinman/dc85f8df76c3a452673ad919c86cf885 to your computer and use it in GitHub Desktop.
A quick Golang code sample for using ApproveAPI to send a magic login link.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"crypto/rand" | |
"encoding/base64" | |
"github.com/approveapi/approveapi-go" | |
"github.com/go-redis/redis" | |
"time" | |
) | |
func GenerateRandomToken(n int) (string, error) { | |
b := make([]byte, n) | |
_, err := rand.Read(b) | |
if err != nil { | |
return nil, err | |
} | |
base64.URLEncoding.EncodeToString(b), err | |
} | |
func CreateAndSendMagicLink(emailAddress string) err { | |
token, err := GenerateRandomToken(32) | |
if err != nil { | |
return err | |
} | |
expiresIn := time.Hour | |
// Use a global redis instance or initialize one here | |
err = redis.Set(token, emailAddress, expiresIn).Err() | |
if err != nil { | |
return err | |
} | |
magicLink := fmt.Sprintf( | |
"https://bookface.com/login?code=%v", token | |
) | |
err = EmailMagicLink(magicLink, emailAddress) | |
} | |
func EmailMagicLink(magicLink string, emailAddress string) error { | |
// Get your API key at https://dashboard.approveapi.com | |
client := approveapi.CreateClient("sk_test_yourapikeyhere") | |
prompt := approveapi.CreatePromptRequest { | |
User: emailAddress, | |
Body: "Click the link below to sign into Bookface.com", | |
ApproveText: "Login", | |
ApproveRedirectUrl: magicLink, | |
} | |
_, _, err := client.ApproveApi.CreatePrompt(prompt) | |
return err | |
} | |
// Invoke this when the user hits | |
// the login URL https://bookface.com/login?code=<token> | |
func AuthenticateToken(token string) { | |
emailAddress, err := redis.Get(token) | |
if err != nil { | |
return err | |
} | |
// Done! The user with username emailAddress is now authenticated! | |
LoginUser(emailAddress) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment