diff options
Diffstat (limited to 'auth')
| -rw-r--r-- | auth/auth.go | 22 | ||||
| -rw-r--r-- | auth/challenge.go | 35 | ||||
| -rw-r--r-- | auth/server.go | 91 | ||||
| -rw-r--r-- | auth/template.go | 63 | 
4 files changed, 76 insertions, 135 deletions
| diff --git a/auth/auth.go b/auth/auth.go index b75c392..9374c72 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -1,6 +1,6 @@  /*  macli - Unofficial CLI-Based MyAnimeList Client -Copyright © 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> +Copyright © 2022-2024 Vidhu Kant Sharma <vidhukant@vidhukant.xyz>  This program is free software: you can redistribute it and/or modify  it under the terms of the GNU General Public License as published by @@ -19,6 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.  package auth  import ( +  mt "vidhukant.com/maltoken"  	"errors"  	"fmt"  	"github.com/spf13/viper" @@ -42,6 +43,10 @@ func init() {  		os.Exit(1)  	}  	userName = currentUser.Username + +  mt.SuccessHTML = fmt.Sprintf(HTMLTemplate, "Login successful.", "Thanks for using macli. You may close this tab now.") +	mt.BadRequestHTML = fmt.Sprintf(HTMLTemplate, "Invalid request.", "Required query parameters are missing.") +	mt.ErrHTML = fmt.Sprintf(HTMLTemplate, "An error occoured.", "%s")  }  // asks for all the details @@ -83,15 +88,16 @@ func Login(tk, clientId string, storeClientId bool) {  		return  	} -	challenge := codeChallenge() -	link := generateLink(clientId, challenge) +  challenge, link := mt.GetChallengeLink(clientId)  	openInBrowser(link) -	listen(clientId, challenge) -} +  res, err := mt.Listen(clientId, challenge, 8000) +	if err != nil { +		fmt.Printf("\x1b[1;31mAn error occoured:\x1b[0m %s\nExiting...\n", err.Error()) +		os.Exit(1) +	} -func generateLink(clientId, challenge string) string { -	return "https://myanimelist.net/v1/oauth2/authorize?response_type=code&client_id=" + clientId + "&code_challenge=" + challenge +  setToken(res["access_token"].(string))  }  func openInBrowser(url string) { @@ -119,8 +125,6 @@ func openInBrowser(url string) {  func Logout() {  	existingToken, _ := keyring.Get(serviceName, userName)  	deleteToken() -	deleteExpiresIn() -	deleteRefreshToken()  	if existingToken != "" {  		fmt.Println("Deleted user credentials.")  	} diff --git a/auth/challenge.go b/auth/challenge.go deleted file mode 100644 index 60161ee..0000000 --- a/auth/challenge.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -macli - Unofficial CLI-Based MyAnimeList Client -Copyright © 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - -package auth - -import ( -  "time" -  "math/rand" -) - -var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") - -func codeChallenge() string { -    rand.Seed(time.Now().UnixNano()) -    b := make([]rune, 128) -    for i := range b { -        b[i] = letterRunes[rand.Intn(len(letterRunes))] -    } -    return string(b) -} diff --git a/auth/server.go b/auth/server.go deleted file mode 100644 index 5bce2aa..0000000 --- a/auth/server.go +++ /dev/null @@ -1,91 +0,0 @@ -/* -macli - Unofficial CLI-Based MyAnimeList Client -Copyright © 2022 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see <http://www.gnu.org/licenses/>. -*/ - -package auth - -import ( -	"context" -  "net/http" -  "net/url" -	"html" -  "encoding/json" -  "os" -  "fmt" -	"errors" -) - -func listen(clientId, verifier string) { -	mux := http.NewServeMux() -	server := &http.Server{Addr: ":8000", Handler: mux} - -	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -		code, codeExists := r.URL.Query()["code"] - -		if codeExists { -			err := getToken(clientId, verifier, code[0]) -			if err != nil { -			  fmt.Fprintf(w, "<p>An error occoured while logging in: %s</p>", html.EscapeString(err.Error())) - -				fmt.Println("Error while requesting an access token from MyAnimeList:", err) -			} else { -				fmt.Fprintf(w, "<p>Login successful! You may close this tab now.</p>") - -				fmt.Println("\x1b[32mYou have successfully logged into macli.\x1b[0m") -				fmt.Println("\x1b[32mYou can close the web browser tab now.\x1b[0m") -			} -		} else { -			fmt.Fprintf(w, "<p>An error occoured while logging in (invalid request)</p>") - -			fmt.Println("An error occoured while logging in (invalid request)") -		} - -		go server.Shutdown(context.Background()) -  }) - -  err := server.ListenAndServe() -  if err != nil && err != http.ErrServerClosed { -    fmt.Println("There was an error initialising the server", err.Error()) -    os.Exit(1) -  } -} - -func getToken(clientId, verifier, code string) error { -  data := url.Values{ -		"client_id": {clientId}, -		"code_verifier": {verifier}, -		"grant_type": {"authorization_code"}, -		"code": {code}, -  } - -  resp, err := http.PostForm("https://myanimelist.net/v1/oauth2/token", data) -  if err != nil { -		return err -  } - -  var res map[string]interface{} -  json.NewDecoder(resp.Body).Decode(&res) - -	if res["error"] != nil { -		return errors.New(fmt.Sprintf("%v (%v)", res["message"], res["error"])) -	} - -	setToken(fmt.Sprintf("%v", res["access_token"])) -	//setRefreshToken(refreshToken) -	//setExpiresIn(expiresIn) -  return nil -} diff --git a/auth/template.go b/auth/template.go new file mode 100644 index 0000000..a16e0e1 --- /dev/null +++ b/auth/template.go @@ -0,0 +1,63 @@ +/* +macli - Unofficial CLI-Based MyAnimeList Client +Copyright © 2022-2024 Vidhu Kant Sharma <vidhukant@vidhukant.xyz> + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public Lice +along with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +package auth + +var HTMLTemplate = ` +<html> +  <head> +    <title>macli - Unofficial MyAnimeList Client</title> +  </head> +  <body> +    <style> +    body { +      background-color: #232627; +      display: flex; +      flex-direction: column; +      justify-content: center; +      gap: 0.5rem; +      align-items: center; +      min-height: 100vh; +    } +    a { +      color: #C678DD; +    } +    #heading, #subheading, #description { +      text-align: center; +      margin: 0; +    } +    #heading { +      color: #C678DD; +      font-size: 2.2em; +    } +    #subheading { +      color: #dfdfdf; +      font-size: 1.2em; +    } +    #description { +      margin-top: 2rem; +      color: lightgray; +      font-size: 1em; +    } +    </style> +    <p id="heading">%s</p> +    <p id="subheading">%s</p> +    <p id="description"><a href="https://macli.vidhukant.com">https://macli.vidhukant.com</a></p> +  </body> +</html> +` |