File: token.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (68 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) 2020, Control Command Inc. All rights reserved.
// Copyright (c) 2019-2021, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package endpoint

import (
	"fmt"
	"net/http"

	"github.com/sylabs/singularity/v4/internal/pkg/remote/credential"
	"github.com/sylabs/singularity/v4/pkg/sylog"
	useragent "github.com/sylabs/singularity/v4/pkg/util/user-agent"
)

// VerifyToken returns an error if a token is not valid against an endpoint.
// If token is provided as an argument, it will verify the provided token.
// If token is "", it will attempt to verify the configured token for the endpoint.
func (ep *Config) VerifyToken(token string) (err error) {
	defer func() {
		if err == nil {
			sylog.Infof("Access Token Verified!")
		}
	}()

	if token == "" {
		token = ep.Token
	}

	sp, err := ep.GetAllServices()
	if err != nil {
		return err
	}

	ts, ok := sp[Token]
	if !ok || len(ts) == 0 {
		return fmt.Errorf("no authentication service found")
	}

	client := &http.Client{
		Timeout: defaultTimeout,
	}
	req, err := http.NewRequest(http.MethodGet, ts[0].URI()+"/v1/token-status", nil)
	if err != nil {
		return err
	}

	req.Header.Set("Authorization", credential.TokenPrefix+token)
	req.Header.Set("User-Agent", useragent.Value())

	res, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("error making request to server: %v", err)
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		convStatus, ok := errorCodeMap[res.StatusCode]
		if !ok {
			convStatus = "Unknown"
		}
		return fmt.Errorf("error response from server: %v", convStatus)
	}

	return nil
}