| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/base64" |
| 7 | "strings" |
| 8 | "unicode/utf8" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 11 | "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // RegisterNative derives the person and lifetime from a live native session in |
| 16 | // the write transaction. The caller can supply only its device key and label. |
| 17 | func (s *DeviceStore) RegisterNative(ctx context.Context, a kernel.Actor, key, label string) (out PersonCredential, err error) { |
| 18 | p, ok := PrincipalFrom(ctx) |
| 19 | if !ok || p.Address == "" || p.Address != a.Address || p.CredentialID != "" || p.Pending || p.SessionHash == "" || s.NativeSession == nil { |
| 20 | return out, ErrUnauthenticated |
| 21 | } |
| 22 | raw, e := base64.RawURLEncoding.Strict().DecodeString(key) |
| 23 | if s.Key == "" || e != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != key || len(label) < 1 || len(label) > 128 || !utf8.ValidString(label) || strings.ContainsAny(label, "\x00\r\n") { |
| 24 | return out, s.Invalid |
| 25 | } |
| 26 | err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 27 | now := s.Now().UTC() |
| 28 | sess, e := s.NativeSession(tx, p.SessionHash) |
| 29 | if e != nil || sess.Method != oficinaid.NativeMethod || sess.Subject != a.Address || !now.Before(sess.At.Add(oficinaid.NativeLifetime)) { |
| 30 | return ErrUnauthenticated |
| 31 | } |
| 32 | if e = s.member(tx, sess.Subject, sess.At.Unix()); e != nil { |
| 33 | return e |
| 34 | } |
| 35 | instance, e := s.Instance(tx) |
| 36 | if e != nil { |
| 37 | return e |
| 38 | } |
| 39 | id := rand.Text() |
| 40 | token := PersonAudience + "." + rand.Text() |
| 41 | out = PersonCredential{ID: id, Token: token, Audience: PersonAudience, InstanceID: instance, ExpiresAt: sess.At.Add(oficinaid.NativeLifetime), Revision: 1} |
| 42 | row := DeviceRecord{ID: id, RequestHash: s.mac("native", id), PublicKey: key, Label: label, InstanceID: instance, Person: sess.Subject, SessionEpoch: sess.At.Unix(), Revision: 1, CreatedAt: now, ExpiresAt: out.ExpiresAt, ApprovedAt: &now, ExchangedAt: &now, TokenHash: s.mac(PersonAudience, token), TokenExpiresAt: out.ExpiresAt, NativeSessionHash: p.SessionHash} |
| 43 | if e = tx.Create(&row).Error; e != nil { |
| 44 | return e |
| 45 | } |
| 46 | return s.Audit(tx, kernel.Actor{Address: sess.Subject}, "person_device.native", id) |
| 47 | }) |
| 48 | if err != nil { |
| 49 | out = PersonCredential{} |
| 50 | } |
| 51 | return |
| 52 | } |
| 53 | |