feat: interactive auth method selection with API token validation

- Add GetToken() as unified auth entry point with method selection
- Prompt [1] OAuth / [2] API token on first launch, save choice
- Validate API tokens against /api/v1/users/self before saving
- Check saved API token validity on reuse; fallback to re-prompt on failure
- Add HTTP status check to GetCourseInfo and GetEnrolledCourses
- Remove --api flag, auth method is now persistent and interactive
This commit is contained in:
2026-06-19 21:17:00 +02:00
parent 666369714b
commit 07fade16d3
5 changed files with 89 additions and 32 deletions

View File

@@ -31,15 +31,11 @@ go build -o canvasarchiver ./cmd/canvasarchiver
./canvasarchiver -vo ./canvasarchiver -vo
``` ```
Or to use a manually generated Canvas API token: 2. On first run, you'll be prompted to choose an authentication method:
```bash - **[1] Login via browser (OAuth)**: Visit the provided URL, authorize, and paste the code
./canvasarchiver --api - **[2] Use Canvas API token**: Enter a manually generated API token (e.g. `12230~...`)
```
2. On first run, you'll be prompted to authenticate: The choice is saved and reused on subsequent runs.
- Visit the provided OAuth URL
- Authorize the application
- Copy the authorization code back to the terminal
3. Enter your Course ID when prompted (or use `-me` to download all enrolled courses) 3. Enter your Course ID when prompted (or use `-me` to download all enrolled courses)
@@ -58,8 +54,6 @@ go build -o canvasarchiver ./cmd/canvasarchiver
| `-vo` | Videos only — scan recordings and all module video items, download everything flat into one directory; skips regular files | | `-vo` | Videos only — scan recordings and all module video items, download everything flat into one directory; skips regular files |
| `-me` | Download all enrolled courses | | `-me` | Download all enrolled courses |
| `-n` | Prefix modules with order numbers `[1]`, `[2]`, etc. | | `-n` | Prefix modules with order numbers `[1]`, `[2]`, etc. |
| `--api` | Use a manually generated Canvas API token instead of OAuth |
## Configuration ## Configuration
@@ -72,9 +66,7 @@ The following constants can be modified in `internal/config/config.go`:
## Authentication ## Authentication
Credentials are stored in `credentials.json` after the first successful login. The refresh token is automatically used for subsequent runs. Credentials are stored in `credentials.json` after the first successful authentication. The chosen method is remembered for subsequent runs — OAuth refresh tokens are automatically refreshed, and API tokens are validated before saving.
With `--api`, enter a manually generated Canvas API token on first use. It is saved to `credentials.json` and reused on later `--api` runs.
## Notes ## Notes

View File

@@ -17,19 +17,12 @@ func main() {
videosOnly := flag.Bool("vo", false, "Videos only mode - download only Panopto videos to a single directory") videosOnly := flag.Bool("vo", false, "Videos only mode - download only Panopto videos to a single directory")
me := flag.Bool("me", false, "Download all enrolled courses") me := flag.Bool("me", false, "Download all enrolled courses")
moduleNumbers := flag.Bool("n", false, "Prefix modules with order numbers [1], [2], etc.") moduleNumbers := flag.Bool("n", false, "Prefix modules with order numbers [1], [2], etc.")
apiToken := flag.Bool("api", false, "Use a manually generated Canvas API token instead of OAuth")
flag.Parse() flag.Parse()
httpClient := &http.Client{} httpClient := &http.Client{}
authenticator := auth.NewAuthenticator(httpClient) authenticator := auth.NewAuthenticator(httpClient)
var accessToken string accessToken, err := authenticator.GetToken()
var err error
if *apiToken {
accessToken, err = authenticator.GetAPIToken()
} else {
accessToken, err = authenticator.GetAccessToken()
}
if err != nil { if err != nil {
fmt.Printf("Authentication failed: %v\n", err) fmt.Printf("Authentication failed: %v\n", err)
return return

View File

@@ -27,7 +27,32 @@ func NewAuthenticator(client *http.Client) *Authenticator {
} }
} }
func (a *Authenticator) GetAccessToken() (string, error) { func (a *Authenticator) GetToken() (string, error) {
creds, err := LoadCredentials()
if err == nil && creds.AuthMethod != "" {
switch creds.AuthMethod {
case "api":
token := strings.TrimSpace(creds.APIToken)
if token == "" {
return a.promptMethod()
}
fmt.Print("[*] Validating saved API token... ")
if err := a.validateAPIToken(token); err != nil {
fmt.Println("FAILED")
fmt.Printf("[!] %v\n", err)
SaveCredentials(&models.Credentials{})
return a.promptMethod()
}
fmt.Println("OK")
return token, nil
case "oauth":
return a.refreshOrLogin()
}
}
return a.promptMethod()
}
func (a *Authenticator) refreshOrLogin() (string, error) {
creds, err := LoadCredentials() creds, err := LoadCredentials()
if err != nil { if err != nil {
return a.login() return a.login()
@@ -52,36 +77,66 @@ func (a *Authenticator) GetAccessToken() (string, error) {
return tr.AccessToken, nil return tr.AccessToken, nil
} }
func (a *Authenticator) GetAPIToken() (string, error) { func (a *Authenticator) promptMethod() (string, error) {
creds, err := LoadCredentials() fmt.Println("Select authentication method:")
if err == nil && strings.TrimSpace(creds.APIToken) != "" { fmt.Println(" [1] Login via browser (OAuth)")
fmt.Println("[*] Reusing saved API token...") fmt.Println(" [2] Use Canvas API token")
return strings.TrimSpace(creds.APIToken), nil fmt.Print("Choice (1/2): ")
input, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
switch strings.TrimSpace(input) {
case "2":
return a.setupAPIToken()
default:
return a.login()
} }
if err != nil {
creds = &models.Credentials{}
} }
func (a *Authenticator) setupAPIToken() (string, error) {
fmt.Print("Enter Canvas API token: ") fmt.Print("Enter Canvas API token: ")
token, err := bufio.NewReader(os.Stdin).ReadString('\n') token, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
return "", err return "", err
} }
token = strings.TrimSpace(token) token = strings.TrimSpace(token)
if token == "" { if token == "" {
return "", fmt.Errorf("empty API token") return "", fmt.Errorf("empty API token")
} }
creds.APIToken = token fmt.Print("[*] Validating API token... ")
if err := SaveCredentials(creds); err != nil { if err := a.validateAPIToken(token); err != nil {
fmt.Println("FAILED")
return "", err return "", err
} }
fmt.Println("OK")
if err := SaveCredentials(&models.Credentials{
AuthMethod: "api",
APIToken: token,
}); err != nil {
return "", err
}
fmt.Println("[+] API token saved.") fmt.Println("[+] API token saved.")
return token, nil return token, nil
} }
func (a *Authenticator) validateAPIToken(token string) error {
req, _ := http.NewRequest("GET", config.BaseURL+"/api/v1/users/self", nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := a.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("invalid token: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return nil
}
func (a *Authenticator) login() (string, error) { func (a *Authenticator) login() (string, error) {
codeVerifier, codeChallenge, err := generatePKCEPair() codeVerifier, codeChallenge, err := generatePKCEPair()
if err != nil { if err != nil {
@@ -211,6 +266,7 @@ func SaveRefreshToken(refreshToken string) error {
creds = &models.Credentials{} creds = &models.Credentials{}
} }
creds.RefreshToken = refreshToken creds.RefreshToken = refreshToken
creds.AuthMethod = "oauth"
return SaveCredentials(creds) return SaveCredentials(creds)
} }

View File

@@ -16,6 +16,13 @@ import (
"git.directme.in/Joren/CanvasArchiver/internal/utils" "git.directme.in/Joren/CanvasArchiver/internal/utils"
) )
func checkAPIResponse(resp *http.Response) error {
if resp.StatusCode < 300 {
return nil
}
return fmt.Errorf("API error: %d", resp.StatusCode)
}
type Client struct { type Client struct {
HTTPClient *http.Client HTTPClient *http.Client
AccessToken string AccessToken string
@@ -48,6 +55,10 @@ func (c *Client) GetCourseInfo() error {
} }
defer resp.Body.Close() defer resp.Body.Close()
if err := checkAPIResponse(resp); err != nil {
return err
}
var course models.Course var course models.Course
json.NewDecoder(resp.Body).Decode(&course) json.NewDecoder(resp.Body).Decode(&course)
@@ -64,6 +75,10 @@ func (c *Client) GetEnrolledCourses() ([]models.Course, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if err := checkAPIResponse(resp); err != nil {
return nil, err
}
var courses []models.Course var courses []models.Course
json.NewDecoder(resp.Body).Decode(&courses) json.NewDecoder(resp.Body).Decode(&courses)
return courses, nil return courses, nil

View File

@@ -1,6 +1,7 @@
package models package models
type Credentials struct { type Credentials struct {
AuthMethod string `json:"auth_method,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"` RefreshToken string `json:"refresh_token,omitempty"`
APIToken string `json:"api_token,omitempty"` APIToken string `json:"api_token,omitempty"`
} }