@@ -53,6 +53,41 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
53
53
httpapi .Write (ctx , rw , http .StatusCreated , codersdk.GenerateAPIKeyResponse {Key : cookie .Value })
54
54
}
55
55
56
+ // Creates a new session key, used for logging in via the CLI.
57
+ func (api * API ) postAPIKey (rw http.ResponseWriter , r * http.Request ) {
58
+ ctx := r .Context ()
59
+ user := httpmw .UserParam (r )
60
+
61
+ if ! api .Authorize (r , rbac .ActionCreate , rbac .ResourceAPIKey .WithOwner (user .ID .String ())) {
62
+ httpapi .ResourceNotFound (rw )
63
+ return
64
+ }
65
+
66
+ lifeTime := time .Hour * 24 * 7
67
+ cookie , err := api .createAPIKey (ctx , createAPIKeyParams {
68
+ UserID : user .ID ,
69
+ LoginType : database .LoginTypePassword ,
70
+ RemoteAddr : r .RemoteAddr ,
71
+ // All api generated keys will last 1 week. Browser login tokens have
72
+ // a shorter life.
73
+ ExpiresAt : database .Now ().Add (lifeTime ),
74
+ LifetimeSeconds : int64 (lifeTime .Seconds ()),
75
+ })
76
+ if err != nil {
77
+ httpapi .Write (ctx , rw , http .StatusInternalServerError , codersdk.Response {
78
+ Message : "Failed to create API key." ,
79
+ Detail : err .Error (),
80
+ })
81
+ return
82
+ }
83
+
84
+ // We intentionally do not set the cookie on the response here.
85
+ // Setting the cookie will couple the browser sesion to the API
86
+ // key we return here, meaning logging out of the website would
87
+ // invalid your CLI key.
88
+ httpapi .Write (ctx , rw , http .StatusCreated , codersdk.GenerateAPIKeyResponse {Key : cookie .Value })
89
+ }
90
+
56
91
func (api * API ) apiKey (rw http.ResponseWriter , r * http.Request ) {
57
92
var (
58
93
ctx = r .Context ()
0 commit comments