aboutsummaryrefslogtreecommitdiff
path: root/model/session.go
blob: 94f527bfdaf3ac37e96a1d9822f88ab6add042c6 (plain)
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
package model

import (
	"errors"
	"strings"
)

var (
	ErrSessionNotFound = errors.New("session not found")
)

type Session struct {
	ID             string
	InstanceDomain string
	AccessToken    string
}

type SessionRepository interface {
	Add(session Session) (err error)
	Update(sessionID string, accessToken string) (err error)
	Get(sessionID string) (session Session, err error)
}

func (s Session) IsLoggedIn() bool {
	return len(s.AccessToken) > 0
}

func (s *Session) Marshal() []byte {
	str := s.InstanceDomain + "\n" + s.AccessToken
	return []byte(str)
}

func (s *Session) Unmarshal(id string, data []byte) error {
	str := string(data)
	lines := strings.Split(str, "\n")

	size := len(lines)
	if size == 1 {
		s.InstanceDomain = lines[0]
	} else if size == 2 {
		s.InstanceDomain = lines[0]
		s.AccessToken = lines[1]
	} else {
		return errors.New("invalid data")
	}

	s.ID = id
	return nil
}