Generate generates an API key, returning the key as a string as well as the database representation. It is the responsibility of the caller to insert it into the database.
(params CreateParams)
| 45 | // database representation. It is the responsibility of the caller to insert it |
| 46 | // into the database. |
| 47 | func Generate(params CreateParams) (database.InsertAPIKeyParams, string, error) { |
| 48 | // Length of an API Key ID. |
| 49 | keyID, err := cryptorand.String(10) |
| 50 | if err != nil { |
| 51 | return database.InsertAPIKeyParams{}, "", xerrors.Errorf("generate API key ID: %w", err) |
| 52 | } |
| 53 | |
| 54 | // Length of an API Key secret. |
| 55 | keySecret, hashedSecret, err := GenerateSecret(22) |
| 56 | if err != nil { |
| 57 | return database.InsertAPIKeyParams{}, "", xerrors.Errorf("generate API key secret: %w", err) |
| 58 | } |
| 59 | |
| 60 | // Default expires at to now+lifetime, or use the configured value if not |
| 61 | // set. |
| 62 | if params.ExpiresAt.IsZero() { |
| 63 | if params.LifetimeSeconds != 0 { |
| 64 | params.ExpiresAt = dbtime.Now().Add(time.Duration(params.LifetimeSeconds) * time.Second) |
| 65 | } else { |
| 66 | params.ExpiresAt = dbtime.Now().Add(params.DefaultLifetime) |
| 67 | params.LifetimeSeconds = int64(params.DefaultLifetime.Seconds()) |
| 68 | } |
| 69 | } |
| 70 | if params.LifetimeSeconds == 0 { |
| 71 | params.LifetimeSeconds = int64(time.Until(params.ExpiresAt).Seconds()) |
| 72 | } |
| 73 | |
| 74 | if len(params.AllowList) == 0 { |
| 75 | params.AllowList = database.AllowList{{Type: policy.WildcardSymbol, ID: policy.WildcardSymbol}} |
| 76 | } |
| 77 | |
| 78 | ip := net.ParseIP(params.RemoteAddr) |
| 79 | if ip == nil { |
| 80 | ip = net.IPv4(0, 0, 0, 0) |
| 81 | } |
| 82 | |
| 83 | bitlen := len(ip) * 8 |
| 84 | |
| 85 | var scopes database.APIKeyScopes |
| 86 | switch { |
| 87 | case len(params.Scopes) > 0: |
| 88 | scopes = params.Scopes |
| 89 | case params.Scope != "": |
| 90 | var scope database.APIKeyScope |
| 91 | switch params.Scope { |
| 92 | case "all": |
| 93 | scope = database.ApiKeyScopeCoderAll |
| 94 | case "application_connect": |
| 95 | scope = database.ApiKeyScopeCoderApplicationConnect |
| 96 | default: |
| 97 | scope = params.Scope |
| 98 | } |
| 99 | scopes = database.APIKeyScopes{scope} |
| 100 | default: |
| 101 | // Default to coder:all scope for backward compatibility. |
| 102 | scopes = database.APIKeyScopes{database.ApiKeyScopeCoderAll} |
| 103 | } |
| 104 |