File: addresses.go

package info (click to toggle)
golang-github-henrybear327-go-proton-api 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,088 kB
  • sloc: sh: 55; makefile: 26
file content (98 lines) | stat: -rw-r--r-- 2,305 bytes parent folder | download
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
package server

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/henrybear327/go-proton-api"
	"golang.org/x/exp/slices"
)

func (s *Server) handleGetAddresses() gin.HandlerFunc {
	return func(c *gin.Context) {
		addresses, err := s.b.GetAddresses(c.GetString("UserID"))
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"Addresses": addresses,
		})
	}
}

func (s *Server) handleGetAddress() gin.HandlerFunc {
	return func(c *gin.Context) {
		address, err := s.b.GetAddress(c.GetString("UserID"), c.Param("addressID"))
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"Address": address,
		})
	}
}

func (s *Server) handlePutAddressEnable() gin.HandlerFunc {
	return func(c *gin.Context) {
		if err := s.b.EnableAddress(c.GetString("UserID"), c.Param("addressID")); err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}
}

func (s *Server) handlePutAddressDisable() gin.HandlerFunc {
	return func(c *gin.Context) {
		if err := s.b.DisableAddress(c.GetString("UserID"), c.Param("addressID")); err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}
}

func (s *Server) handleDeleteAddress() gin.HandlerFunc {
	return func(c *gin.Context) {
		if err := s.b.DeleteAddress(c.GetString("UserID"), c.Param("addressID")); err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}
}

func (s *Server) handlePutAddressesOrder() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req proton.OrderAddressesReq

		if err := c.BindJSON(&req); err != nil {
			c.AbortWithStatus(http.StatusBadRequest)
			return
		}

		addresses, err := s.b.GetAddresses(c.GetString("UserID"))
		if err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}

		if len(req.AddressIDs) != len(addresses) {
			c.AbortWithStatus(http.StatusBadRequest)
			return
		}

		for _, address := range addresses {
			if !slices.Contains(req.AddressIDs, address.ID) {
				c.AbortWithStatus(http.StatusBadRequest)
				return
			}
		}

		if err := s.b.SetAddressOrder(c.GetString("UserID"), req.AddressIDs); err != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
	}
}