99 "net/http"
1010 "time"
1111
12+ "github.com/davecgh/go-spew/spew"
1213 "github.com/gin-gonic/gin"
1314 "github.com/jinzhu/gorm"
1415 "github.com/jinzhu/gorm/dialects/postgres"
@@ -33,6 +34,8 @@ func (h *Headscale) RegisterWebAPI(c *gin.Context) {
3334 return
3435 }
3536
37+ spew .Dump (c .Params )
38+
3639 c .Data (http .StatusOK , "text/html; charset=utf-8" , []byte (fmt .Sprintf (`
3740 <html>
3841 <body>
@@ -71,6 +74,7 @@ func (h *Headscale) RegistrationHandler(c *gin.Context) {
7174 c .String (http .StatusInternalServerError , "Very sad!" )
7275 return
7376 }
77+
7478 db , err := h .db ()
7579 if err != nil {
7680 log .Printf ("Cannot open DB: %s" , err )
@@ -359,21 +363,59 @@ func (h *Headscale) getMapKeepAliveResponse(mKey wgcfg.Key, req tailcfg.MapReque
359363}
360364
361365func (h * Headscale ) handleNewServer (c * gin.Context , db * gorm.DB , idKey wgcfg.Key , req tailcfg.RegisterRequest ) {
362- mNew := Machine {
366+ m := Machine {
363367 MachineKey : idKey .HexString (),
364368 NodeKey : wgcfg .Key (req .NodeKey ).HexString (),
365369 Expiry : & req .Expiry ,
366370 Name : req .Hostinfo .Hostname ,
367371 }
368- if err := db .Create (& mNew ).Error ; err != nil {
372+ if err := db .Create (& m ).Error ; err != nil {
369373 log .Printf ("Could not create row: %s" , err )
370374 return
371375 }
372- resp := tailcfg.RegisterResponse {
373- AuthURL : fmt .Sprintf ("%s/register?key=%s" ,
374- h .cfg .ServerURL , idKey .HexString ()),
376+
377+ resp := tailcfg.RegisterResponse {}
378+
379+ if req .Auth .AuthKey != "" {
380+ pak , err := h .checkKeyValidity (req .Auth .AuthKey )
381+ if err != nil {
382+ resp .MachineAuthorized = false
383+ respBody , err := encode (resp , & idKey , h .privateKey )
384+ if err != nil {
385+ log .Printf ("Cannot encode message: %s" , err )
386+ c .String (http .StatusInternalServerError , "" )
387+ return
388+ }
389+ c .Data (200 , "application/json; charset=utf-8" , respBody )
390+ return
391+ }
392+ ip , err := h .getAvailableIP ()
393+ if err != nil {
394+ log .Println (err )
395+ return
396+ }
397+
398+ m .IPAddress = ip .String ()
399+ m .NamespaceID = pak .NamespaceID
400+ m .AuthKeyID = uint (pak .ID )
401+ m .Registered = true
402+ db .Save (& m )
403+
404+ resp .MachineAuthorized = true
405+ resp .User = * pak .Namespace .toUser ()
406+ respBody , err := encode (resp , & idKey , h .privateKey )
407+ if err != nil {
408+ log .Printf ("Cannot encode message: %s" , err )
409+ c .String (http .StatusInternalServerError , "Extremely sad!" )
410+ return
411+ }
412+ c .Data (200 , "application/json; charset=utf-8" , respBody )
413+ return
375414 }
376415
416+ resp .AuthURL = fmt .Sprintf ("%s/register?key=%s" ,
417+ h .cfg .ServerURL , idKey .HexString ())
418+
377419 respBody , err := encode (resp , & idKey , h .privateKey )
378420 if err != nil {
379421 log .Printf ("Cannot encode message: %s" , err )
0 commit comments