summaryrefslogtreecommitdiff
path: root/server/user/command.go
blob: b4c6d5fb9c89401829243bca8f0792fe0966e96e (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package user

import (
	"citrons.xyz/talk/server/session"
	"citrons.xyz/talk/proto"
)

func (u *User) SendRequest(r session.Request) {
	switch r.Cmd.Kind {

	case "update":
		if r.From.UserId != u.Id() {
			r.Reply(proto.Fail{"forbidden", "", nil}.Cmd())
			return
		}
		if len(r.Cmd.Args) != 1 {
			r.ReplyInvalid()
			return
		}
		upd := r.Cmd.Args[0]
		if upd.Kind != "u" {
			r.ReplyInvalid()
			return
		}
		name := u.name
		status := u.status
		for k, v := range upd.Fields {
			switch k {
			case "":
				name = v
			case "status":
				status = v
			default:
				r.ReplyInvalid()
				return
			}
		}
		if len(status) > 512 {
			r.Reply(proto.Fail{"too-long", "", nil}.Cmd())
			return
		}
		u.status = status
		if name != u.name {
			err := u.Rename(name)
			if err != nil {
				r.Reply(err.Cmd())
				return
			}
		}
		u.Save()
		u.Stream.Event(r.Cmd)
		r.ReplyOk()

	case "auth-update":
		if r.From.UserId != u.Id() {
			r.Reply(proto.Fail{"forbidden", "", nil}.Cmd())
			return
		}
		if !u.anonymous && !r.From.PasswordAuthed {
			r.Reply(proto.Fail{"password-required", "", nil}.Cmd())
			return
		}
		if len(r.Cmd.Args) != 1 {
			r.ReplyInvalid()
			return
		}
		upd := r.Cmd.Args[0]
		switch upd.Kind {
		case "password":
			var password string
			for k, v := range upd.Fields {
				switch k {
				case "":
					password = v
				default:
					r.ReplyInvalid()
				}
			}
			if password == "" {
				r.ReplyInvalid()
				return
			}
			u.SetPassword(password)
			r.From.PasswordAuthed = true
			r.ReplyOk()
		default:
			r.ReplyInvalid()
			return
		}

	case "i":
		r.Reply(proto.NewCmd("i", "", u.InfoFor(r.From.UserId)))

	case "s":
		r.From.Subscribe(&u.Stream)
		r.Reply(proto.NewCmd("i", "", u.InfoFor(r.From.UserId)))

	case "u":
		r.From.Unsubscribe(&u.Stream)
		r.ReplyOk()

	default:
		r.ReplyInvalid()
	}
}