├── .gitignore
├── API.md
├── CANARY.asc
├── LICENSE
├── README.md
├── auth
├── auth.go
└── common.go
├── code_of_conduct.md
├── component
├── cmp_all_test.go
├── cmp_asset.go
├── cmp_category.go
├── cmp_checklist.go
├── cmp_difficulty.go
├── cmp_form.go
├── cmp_item.go
├── cmp_subcategory.go
├── common.go
├── meta.go
├── meta_test.go
├── parser.go
├── resource_parser.go
├── resource_parser_test.go
└── sort.go
├── go.mod
├── go.sum
├── models
└── user.go
├── repo
├── random.go
├── repo.go
└── repo_handlers.go
├── tent.go
├── tent
├── cmd
│ ├── root.go
│ ├── run.go
│ ├── transifex.go
│ ├── transifex_download.go
│ └── transifex_upload.go
└── main.go
├── transifex
├── client.go
└── common.go
└── utils
├── idgen.go
└── persistence.go
/.gitignore:
--------------------------------------------------------------------------------
1 | out
2 | vendor
3 | translations
4 | tent.exe
5 | .tent.yaml
--------------------------------------------------------------------------------
/API.md:
--------------------------------------------------------------------------------
1 | # Tent API
2 |
3 | ## General
4 |
5 | ### http Methods
6 |
7 | - GET: View
8 | - POST: Create
9 | - PUT: Update
10 | - DELETE: Delete
11 |
12 | ### Error Response
13 | ```
14 | {
15 | "error": "message with details"
16 | }
17 | ```
18 |
19 | ## Categories
20 |
21 | ### List
22 | **GET** /api/repo/ (200)
23 |
24 | **Sample Response**:```{
25 | "categories": [
26 | "catid_1",
27 | "catid_2"
28 | ]
29 | }```
30 |
31 | ### Details
32 | **GET** /api/repo/category/:category _(200 - 404)_
33 |
34 | **Sample Response**:```{
35 | "name": "Category name",
36 | "subcategories": [
37 | "subid_1",
38 | "subid_2"
39 | ]
40 | }```
41 |
42 | ### Create
43 | **POST** /api/repo/category/:category _(201 - 409, 503)_
44 |
45 | **Request Body**:```{
46 | "name": "Category name"
47 | }```
48 |
49 | ### Update
50 | **PUT** /api/repo/category/:category _(204 - 503)_
51 |
52 | **Request Body**:```{
53 | "name": "Category name"
54 | }```
55 |
56 | ### Delete
57 | **DELETE** /api/repo/category/:category _(204 - 503)_
58 |
59 | ## Subcategories
60 |
61 | ### Details
62 | **GET** /api/repo/category/:category/:sub _(200 - 404)_
63 |
64 | **Sample Response**:```{
65 | "name": "Subcategory name",
66 | "items": [
67 | "itemid_1",
68 | "itemid_2"
69 | ]
70 | }```
71 |
72 | ### Create
73 | **POST** /api/repo/category/:category/:sub _(201 - 409, 503)_
74 |
75 | **Request Body**:```
76 | {
77 | "name": "Subcategory name"
78 | }```
79 |
80 | ### Update
81 | **PUT** /api/repo/category/:category/:sub _(204 - 503)_
82 |
83 | **Request Body**:```
84 | {
85 | "name": "Category name"
86 | }```
87 |
88 | ### Delete
89 | **DELETE** /api/repo/category/:category/:sub _(204 - 503)_
90 |
91 | ## Items
92 |
93 | ### Details
94 | **GET** /api/repo/category/:category/:sub/item/:item _(200 - 404)_
95 |
96 | **Sample Response**:
97 | ```
98 | {
99 | "hash": "sha1",
100 | "title": "Item Title",
101 | "body": "
Sample Body
some text
",
102 | "difficulty": "Beginner"
103 | }```
104 |
105 | ### Create
106 | **POST** /api/repo/category/:category/:sub/item/:item _(201 - 503)_
107 |
108 | **Request Body**:
109 | ```
110 | {
111 | "title": "Item Title",
112 | "body": "Sample Body
some text
",
113 | "difficulty": "Beginner"
114 | }```
115 |
116 | ### Update
117 | **PUT** /api/repo/category/:category/:sub/item/:item _(204 - 409, 503)_
118 |
119 | **Request Body**:
120 | ```
121 | {
122 | "hash": "sha1",
123 | "title": "Item Title",
124 | "body": "Sample Body
some text
",
125 | "difficulty": "Beginner"
126 | }```
127 |
128 |
129 | ### Delete
130 | **DELETE** /api/repo/category/:category/:sub/item/:item _(204 - 503)_
--------------------------------------------------------------------------------
/CANARY.asc:
--------------------------------------------------------------------------------
1 | -----BEGIN PGP SIGNED MESSAGE-----
2 | Hash: SHA512
3 |
4 | Status: All good
5 | Period: July 1 to December 31, 2020
6 |
7 | As of 28th of October 2020 [1] Security First, Umbrella and it's ownership has shifted for privacy and operational reasons from it's UK Company (Global Security First Ltd.) to an Irish Company (Security First Technologies Ltd).
8 |
9 | Neither has ever received any National Security Letters or FISA court orders, and we have not been subject to any gag order by a FISA court, or any other similar court of any government in the UK, Ireland, EU or anywhere else on the globe. Security First has never placed any backdoors in our hardware or software and has not received any requests to do so. Security First has never disclosed any user information or communications to any third party.
10 |
11 | Security First intends to update this report approximately once per quarter.
12 |
13 | [1] EU accused of abandoning migrants to the sea with shift to drone surveillance
14 |
15 | https://www.theguardian.com/global-development/2020/oct/28/eu-accused-of-abandoning-migrants-to-the-sea-with-shift-to-drone-surveillance
16 |
17 | Notes:
18 |
19 | This scheme is not infallible. Although signing the declaration makes it impossible for a third party to produce arbitrary declarations, it does not prevent them from using force to coerce Security First to produce false declarations. The news clip in the signed message serves to demonstrate that that update could not have been created prior to that date. It shows that a series of these updates were not created in advance and posted on this page.
20 |
21 | -----BEGIN PGP SIGNATURE-----
22 |
23 | iQIzBAEBCgAdFiEEM1RODmn7IaEdZhdj/7m1viwdO00FAl+ZiaAACgkQ/7m1viwd
24 | O03phQ/6Aj+gGL88ISTsHc/bluZdJWSB6TVdp1KEYFwfGhhBdBNEjfpr6b3Bqlm5
25 | Com6HhnLlEYMuikHETYRYZnQeEAxj820mL9nosoc8pHjoXJgwY8jTzzhvlgAP+ku
26 | UAemxYXJuAtGPrK56aVDDuUhvbyJqHTfSnre2E/CBjYeqZWQF/5sWodGMoLZHB5L
27 | S0yhjhYhqZWwubHKFUlmtEEHSLS4jCCRx7yG1eVddlQXzdGYqTBJxqfiBd07Vywl
28 | +ZPHsPVrLBNRLjt8zvbaj/sIrhoidLoTbkAEIM5Q4GOODTPmrL4KHJWeyL9olECX
29 | jlYpUj8a76B2ccY9pTt3Lp3a4Ae9/tBVsG/IhDpRZuYj9ZFuE19jHvbsFkHIiwau
30 | Gtym6xn/fmet6bng5acWnRbQFmd97X9YAvAH0uJ20A7yCgRK4DT0GfTPtw7Clgfo
31 | CAy4WlX6IT8FnNcY7c/ULT3FhuWFU8mvZogWE/lrRX6PyjJr23lV67IXqcaKI4Nm
32 | /D1QPNIjVG3lCeNxy8zRBYJzCWwqw4dIe7ZyokjI1ewkAKzI+QJ2cS5Mp2liWY/u
33 | sbbG3ATyxqNofZMtdMtfMHstX24g4IJvewTr9nR+hltA8HGHpHPDqn1SpQsSeoT4
34 | l83BVps2tqVAnsPcELbiTUUHryztDdighy7TcrOoVYNuzAzQFLQ=
35 | =nOoL
36 | -----END PGP SIGNATURE-----
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tent
2 |
3 | Tent is a content management system that leverages a Github Repository to store its content and its history.
4 | That allows Tent to use the [**Content as code**](https://github.com/iilab/contentascode) standard.
5 |
6 | # Configuration
7 |
8 | Some steps are required for using tent.
9 |
10 | # Server
11 | Tent is best run on the following infrastructure:
12 |
13 | -Ubuntu Server 16.04.3 LTS
14 |
15 | -Windows 2012
16 |
17 | We recommend it running with a minimum of 1GB RAM, 1 GB of storage.
18 |
19 | # Services
20 | Location, local laws and choice of service provider is important when considering the security of any deployment.
21 |
22 | For NGOs, we particularly recommend the use https://eclips.is - run by a privacy friendly provider who provide free server space in multiple jurisdictions.
23 |
24 | # Security
25 | We highly recommend hardening of any server that Tent is running on.
26 |
27 | For example for Linux we recommend using the following guides:
28 |
29 | [Ubuntu Server Hardening Guide: Quick and Secure]
30 | (https://linux-audit.com/ubuntu-server-hardening-guide-quick-and-secure/)
31 |
32 | [Best practices for hardening a new server]
33 | (https://www.digitalocean.com/community/questions/best-practices-for-hardening-new-sever-in-2017)
34 |
35 | For Windows 2012 we recommend using the following guides:
36 |
37 | [Windows Sever 2012 Hardening Checklist]
38 | (https://wikis.utexas.edu/display/ISO/Windows+Server+2012+R2+Hardening+Checklist)
39 |
40 | [Server Hardening: Windows Server 2012]
41 | (https://technet.microsoft.com/en-us/security/jj720323.aspx)
42 |
43 | We also recommend the usage of server auditing measurements such as those provided by the [Center for Internet Security](Center for Internet Security) and [SCAP](https://scap.nist.gov/).
44 |
45 | Auditing tools we recommend include CIS-CAT, [Open Scap](https://www.open-scap.org) and [Lynis](https://cisofy.com/lynis/). For non-profits we also want to highlight the availability of a number of discount or free tools that can be used to help ensure the security of a Tent deployment:
46 |
47 | [Tenable Nessus Non-Profit Donation](https://www.tenable.com/about-tenable/tenable-in-the-community/tenable-charitable-organization-subscription-program)
48 |
49 | [Crowdstrike Non-Profit Donation]
50 | (https://www.crowdstrike.org)
51 |
52 | For enhanced security of the Tent server, we recommend the conducting of a penetration test according to the [SAFETAG](https://safetag.org/) methodology - designed specifically for civil society groups at risk.
53 |
54 |
55 |
56 | ## Project
57 |
58 | Create the repository that will store your content, by using this [page](https://github.com/new).
59 | Once it's created go into project **Settings** in the **Webhooks** menu.
60 | Here you can create a new hook with the following URL
61 | `https://YourAppPublicDomain/api/repo/update` and default settings.
62 |
63 | ## OAuth
64 |
65 | Tent needs an OAuth application configured in order to work.
66 | The application can be bound to an user (using this [form](https://github.com/settings/applications/new))
67 | or an organization (`https://github.com/organizations/YourOrg/settings/applications/new`).
68 |
69 | Once it's created **client id** and **client secret** will be available.
70 | You can also change several other parameters including *Authorization callback URL*:
71 | this should be set as `https://YourAppPublicDomain/auth/callback`.
72 | You will need these for the configuration file.
73 |
74 | ## Binary
75 |
76 | Download the latest version of the [binary](https://github.com/securityfirst/tent/releases/latest) or build it from source.
77 | In order to do so install [latest version](https://golang.org/dl/) of Go
78 | then execute `go get github.com/securityfirst/tent/tent`.
79 | This will install it in your `$GOPATH` (that should be `~/go/bin`)
80 |
81 | ## Configuration
82 |
83 | Now you create a configuration file named `.tent.yaml` in your `$HOME` folder using the following contents as example.
84 |
85 | ```yaml
86 | Github:
87 | Handler: "awesomeorg" # Github user of the project
88 | Project: "myawesomeproject" # Project name
89 | Branch: "master" # Project branch (default is master)
90 | Config:
91 | Id: "YOUR_CLIENT_ID" # replace with your client_id
92 | Secret: "YOUR_CLIENT_SECRET" # replace with your secret
93 | OAuthHost: "https://YourAppPublicDomain" # replace with the endpoint you specified
94 | Login:
95 | Endpoint: "/auth/login"
96 | Logout:
97 | Endpoint: "/auth/logout"
98 | Callback:
99 | Endpoint: "/auth/callback"
100 | State: "whatever"
101 | Server:
102 | Port: 80 # Port used by the App
103 | Transifex:
104 | Project: "project-name"
105 | Username: "user"
106 | Password: "password"
107 | Language: en
108 | ```
109 |
110 | # Run
111 |
112 | Once everything is ready you can start the app using `tent.exe run`. You can also specify the `--config file` if you want to use a specific configuration.
113 |
114 | # Repo structure
115 |
116 | The repo have the following structure
117 |
118 | ## Assets
119 |
120 | `assets` is a folder in the project root, containing binary files (ie *pictures*) for your project.
121 | They are available at the `/api/repo/asset/id` endpoint.
122 |
123 | ## Forms
124 |
125 | `forms_xx` (ie *forms_en*) is a folder containing forms file. Supports localisation (you can put a translated version in *forms_es* for instance) and has the following structure:
126 |
127 | ```md
128 | [Name]: # (Title of the form)
129 |
130 | [Type]: # (screen)
131 | [Name]: # (Name of the first screen)
132 |
133 | [Type]: # (text_area)
134 | [Name]: # (input_name)
135 | [Label]: # (Label of the input)
136 |
137 | [Type]: # (screen)
138 | [Name]: # (Another scree)
139 |
140 | [Type]: # (multiple_choice)
141 | [Name]: # (another-input)
142 | [Label]: # (Label for the input)
143 | [Options]: # (Option 1;Option 2;Option 3)
144 | ```
145 |
146 | ## Content
147 |
148 | `content_xx` is the main content directory and it support localisation, same as forms.
149 | It contains 3 level of hierachy (Category, Subcategory, Difficulty) and inside a Checklist and a series of Items
150 |
151 | ```
152 | - contents_en
153 | - category_id
154 | - .metadata.md # Category descriptor
155 | - subcategory_id
156 | - .metadata.md # Subcategory descriptor
157 | - difficulty_id
158 | - .checks.md # Checklist
159 | - .metadata.md # Difficulty descriptor
160 | - item_1.md # Item
161 | ```
162 |
163 | # Sample Repo
164 |
165 | This a the repo used by tent in the [Umbrella App](https://play.google.com/store/apps/details?id=org.secfirst.umbrella): https://github.com/securityfirst/tent-content
166 | This is another sample repo, with sample content, that you can use to check how things works: https://github.com/securityfirst/tent-example
167 |
168 | # New! Branches
169 |
170 | You can work on a specific branch of your content project, this is very usefull for testing purpose (i.e. a big update on content).
171 |
172 | # Troubleshot
173 |
174 | When you execute `tent run` you can check if the app does the checkout correctly:
175 |
176 | ```
177 | Checkout with 5ecb0438dc9aec32e4f5d4572584cd9c50b53055 refs/remotes/origin/master
178 | ```
179 |
180 | If some files is not formatted correctly and raises an error you will see something like:
181 |
182 | ```
183 | Parsing failed: [contents]filepath/file.md - Invalid content
184 | ```
185 |
186 | # Localisation
187 |
188 | You can upload the app content to transifex for translation with the command `tent transifex upload`
189 |
190 | After translations are done you can use `tent transifex download` to import them.
191 |
--------------------------------------------------------------------------------
/auth/auth.go:
--------------------------------------------------------------------------------
1 | package auth
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "net/http"
7 | "path"
8 | "strings"
9 |
10 | "github.com/gin-gonic/gin"
11 | "github.com/google/go-github/github"
12 | "golang.org/x/oauth2"
13 |
14 | "github.com/securityfirst/tent/models"
15 | )
16 |
17 | const (
18 | sessionName = "github-auth"
19 | githubUser = "github-email"
20 | )
21 |
22 | // NewEngine creates a new Engine using and adds the handle for authentication
23 | func NewEngine(conf Config, root *gin.RouterGroup) *Engine {
24 | var e = Engine{
25 | config: conf.OAuth(root),
26 | cache: make(map[string]models.User),
27 | state: conf.State,
28 | }
29 | conf.Login.Redirect = e.config.AuthCodeURL(e.state, oauth2.AccessTypeOnline)
30 | conf.Callback.Redirect = path.Clean(root.BasePath() + conf.Callback.Redirect)
31 | conf.Logout.Redirect = path.Clean(root.BasePath() + conf.Logout.Redirect)
32 | root.GET(conf.Login.Endpoint, func(c *gin.Context) {
33 | c.Redirect(http.StatusTemporaryRedirect, conf.Login.Redirect)
34 | })
35 | root.GET(conf.Logout.Endpoint, func(c *gin.Context) {
36 | c.SetCookie(githubUser, "", -1, "/", "", false, false)
37 | c.Redirect(http.StatusTemporaryRedirect, conf.Logout.Redirect)
38 | })
39 | root.GET(conf.Callback.Endpoint, func(c *gin.Context) {
40 | if errString := c.Query("error"); errString != "" {
41 | log.Printf("Service responded with error: %s", errString)
42 | c.JSON(http.StatusInternalServerError, gin.H{"error": errString})
43 | return
44 | }
45 | state := c.Query("state")
46 | if state != conf.State {
47 | log.Printf("Invalid oauth state, expected %q, got %q", conf.State, state)
48 | c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid oauth state"})
49 | return
50 | }
51 | code := c.Query("code")
52 | token, err := e.config.Exchange(oauth2.NoContext, code)
53 | if err != nil || !token.Valid() {
54 | log.Printf("Cannot get Token: %s", err)
55 | c.Redirect(http.StatusTemporaryRedirect, "/")
56 | return
57 | }
58 | c.SetCookie(githubUser, token.AccessToken, 614880, "/", "", false, false)
59 | c.JSON(200, token)
60 | })
61 | return &e
62 | }
63 |
64 | // Engine is e struct that eases Github OAuth and resource handling
65 | type Engine struct {
66 | config *oauth2.Config
67 | state string
68 | cache map[string]models.User
69 | }
70 |
71 | func (e *Engine) EnsureUser(c *gin.Context) {
72 | var token string
73 | if auth := c.Request.Header.Get("Authorization"); auth != "" {
74 | parts := strings.Split(auth, " ")
75 | if len(parts) != 2 || parts[0] != "Bearer" {
76 | c.JSON(http.StatusBadRequest, gin.H{"error": "invalid authorization"})
77 | c.Abort()
78 | return
79 | }
80 | token = parts[1]
81 | } else {
82 | cookie, err := c.Cookie(githubUser)
83 | if err != nil && err != http.ErrNoCookie {
84 | c.JSON(http.StatusBadRequest, gin.H{"error": "invalid cookie"})
85 | c.Abort()
86 | return
87 | }
88 | token = cookie
89 | }
90 | if token == "" {
91 | c.JSON(http.StatusUnauthorized, gin.H{"error": "access denied"})
92 | c.Abort()
93 | return
94 | }
95 | if err := e.fetchUser(token); err != nil {
96 | c.JSON(http.StatusBadRequest, gin.H{"error": err})
97 | c.Abort()
98 | return
99 | }
100 | c.Set("token", token)
101 | c.Set("user", e.cache[token])
102 | }
103 |
104 | func (e *Engine) fetchUser(token string) error {
105 | if _, ok := e.cache[token]; ok {
106 | return nil
107 | }
108 | u, _, err := github.NewClient(e.config.Client(oauth2.NoContext, &oauth2.Token{AccessToken: token})).Users.Get(oauth2.NoContext, "")
109 | if err != nil {
110 | return fmt.Errorf("Cannot get User: %s", err)
111 | }
112 | var email string
113 | if u.Email != nil {
114 | email = *u.Email
115 | } else {
116 | email = *u.Login + "@tent.org"
117 | }
118 | e.cache[token] = models.User{Name: *u.Name, Login: *u.Login, Email: email}
119 | return nil
120 | }
121 |
--------------------------------------------------------------------------------
/auth/common.go:
--------------------------------------------------------------------------------
1 | package auth
2 |
3 | import (
4 | "fmt"
5 | "path"
6 |
7 | "github.com/gin-gonic/gin"
8 |
9 | "golang.org/x/oauth2"
10 | lib "golang.org/x/oauth2/github"
11 | )
12 |
13 | // HandleConf contains info about and Handler
14 | type HandleConf struct {
15 | Endpoint string
16 | Redirect string
17 | }
18 |
19 | // Basic configuration for an Auth
20 | type Config struct {
21 | ID string
22 | Secret string
23 | OAuthHost string
24 | Host string
25 | State string
26 | Login HandleConf
27 | Logout HandleConf
28 | Callback HandleConf
29 | }
30 |
31 | // OAuth return the oauth2 configuration struct
32 | func (c *Config) OAuth(root *gin.RouterGroup) *oauth2.Config {
33 | return &oauth2.Config{
34 | ClientID: c.ID,
35 | ClientSecret: c.Secret,
36 | RedirectURL: fmt.Sprint(c.OAuthHost, path.Clean(root.BasePath()+c.Callback.Endpoint)),
37 | Endpoint: lib.Endpoint,
38 | Scopes: []string{"user:email", "repo"},
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/code_of_conduct.md:
--------------------------------------------------------------------------------
1 |
2 | # Umbrella Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in Umbrella a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Umbrella leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Umbrella leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all Umbrella spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing Umbrella include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | info@secfirst.org.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].
120 |
121 | Community Impact Guidelines were inspired by
122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123 |
124 | For answers to common questions about this code of conduct, see the FAQ at
125 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available
126 | at [https://www.contributor-covenant.org/translations][translations].
127 |
128 | [homepage]: https://www.contributor-covenant.org
129 | [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
130 | [Mozilla CoC]: https://github.com/mozilla/diversity
131 | [FAQ]: https://www.contributor-covenant.org/faq
132 | [translations]: https://www.contributor-covenant.org/translations
133 |
134 |
--------------------------------------------------------------------------------
/component/cmp_all_test.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "testing"
5 |
6 | . "gopkg.in/check.v1"
7 | git "gopkg.in/src-d/go-git.v4"
8 | "gopkg.in/src-d/go-git.v4/plumbing"
9 | "gopkg.in/src-d/go-git.v4/storage/memory"
10 | )
11 |
12 | func TestAll(t *testing.T) {
13 | TestingT(t)
14 | }
15 |
16 | var _ = Suite(&CmpSuite{})
17 |
18 | type CmpSuite struct{}
19 |
20 | func (*CmpSuite) TestParse(c *C) {
21 | r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: repoAddress("securityfirst", "tent-example")})
22 | c.Assert(err, IsNil)
23 | err = r.Fetch(&git.FetchOptions{})
24 | c.Assert(err, Equals, git.NoErrAlreadyUpToDate)
25 | hash, err := r.Reference(plumbing.ReferenceName("refs/heads/master"), false)
26 | c.Assert(err, IsNil)
27 | commit, err := r.CommitObject(hash.Hash())
28 | c.Assert(err, IsNil)
29 | tree, err := commit.Tree()
30 | c.Assert(err, IsNil)
31 | var t Parser
32 | err = t.Parse(tree)
33 | c.Assert(err, IsNil)
34 | c.Logf("%v Assets", len(t.Assets()))
35 | for _, cat := range t.Categories()["en"] {
36 | c.Log(cat.Name)
37 | for _, sub := range cat.subcategories {
38 | for _, dif := range sub.difficulties {
39 | c.Logf("\t%q %q, items:%v checks:%v", sub.Name, dif.Descr, len(dif.items), len(dif.checklist.Checks))
40 | }
41 | }
42 | }
43 | }
44 |
45 | func (CmpSuite) TestForm(c *C) {
46 | var f Form
47 |
48 | path := `forms_en/formid.md`
49 | contents := `[Name]: # (Form Name)
50 |
51 | [Type]: # (screen)
52 | [Name]: # (Screen 1)
53 |
54 | [Type]: # (text_input)
55 | [Name]: # (text_1)
56 | [Label]: # (Label1)
57 | [Value]: # (value1)
58 | [Options]: # ()
59 | [Hint]: # (hint1)
60 | [Lines]: # (1)
61 |
62 | [Type]: # (screen)
63 | [Name]: # (Screen 2)
64 |
65 | [Type]: # (single_choice)
66 | [Name]: # (choice_1)
67 | [Label]: # (Label2)
68 | [Value]: # ()
69 | [Options]: # (option1|option2|option3)
70 | [Hint]: # (hint2)
71 | [Lines]: # (0)`
72 |
73 | c.Assert(f.SetPath(path), IsNil)
74 | c.Assert(f.SetContents(contents), IsNil)
75 |
76 | c.Assert(f.Path(), Equals, path)
77 | c.Assert(f.Contents(), Equals, contents)
78 |
79 | c.Logf("%v", f)
80 | }
81 |
--------------------------------------------------------------------------------
/component/cmp_asset.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | )
7 |
8 | type Asset struct {
9 | ID string `json:"id"`
10 | Hash string `json:"hash,omAssetpty"`
11 | Content string `json:"content"`
12 | }
13 |
14 | func (a *Asset) Resource() Resource {
15 | return Resource{}
16 | }
17 |
18 | func (*Asset) HasChildren() bool {
19 | return false
20 | }
21 |
22 | func (a *Asset) SHA() string {
23 | return a.Hash
24 | }
25 |
26 | func (i *Asset) Path() string {
27 | return fmt.Sprintf("assets/%s", i.ID)
28 | }
29 |
30 | var assetPath = regexp.MustCompile("assets/([^/]+)")
31 |
32 | func (i *Asset) SetPath(filepath string) error {
33 | p := assetPath.FindStringSubmatch(filepath)
34 | if len(p) == 0 {
35 | return ErrContent
36 | }
37 | i.ID = p[1]
38 | return nil
39 | }
40 |
41 | func (a *Asset) Contents() string {
42 | return a.Content
43 | }
44 |
45 | func (a *Asset) SetContents(contents string) error {
46 | a.Content = contents
47 | return nil
48 | }
49 |
--------------------------------------------------------------------------------
/component/cmp_category.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "regexp"
7 | )
8 |
9 | type Category struct {
10 | ID string `json:"id"`
11 | Name string `json:"name"`
12 | Hash string `json:"hash"`
13 | Locale string `json:"-"`
14 | Order float64 `json:"-"`
15 | subcategories []*Subcategory
16 | }
17 |
18 | func (c *Category) Resource() Resource {
19 | return Resource{
20 | Slug: c.ID,
21 | Content: []map[string]string{
22 | map[string]string{"name": c.Name},
23 | },
24 | }
25 | }
26 |
27 | func (c *Category) HasChildren() bool {
28 | return len(c.subcategories) != 0
29 | }
30 |
31 | func (c *Category) SHA() string {
32 | return c.Hash
33 | }
34 |
35 | func (c *Category) Tree(html bool) interface{} {
36 | var subs = make([]interface{}, 0, len(c.subcategories))
37 | for i := range c.subcategories {
38 | subs = append(subs, c.subcategories[i].Tree(html))
39 | }
40 | return map[string]interface{}{
41 | "id": c.ID,
42 | "name": c.Name,
43 | "subcategories": subs,
44 | }
45 | }
46 |
47 | func (c *Category) MarshalJSON() ([]byte, error) {
48 | var m = map[string]interface{}{
49 | "name": c.Name,
50 | "subcategories": c.Subcategories(),
51 | }
52 | if c.Hash != "" {
53 | m["hash"] = c.Hash
54 | }
55 | return json.Marshal(m)
56 | }
57 |
58 | func (c *Category) Sub(ID string) *Subcategory {
59 | for _, v := range c.subcategories {
60 | if v.ID == ID {
61 | return v
62 | }
63 | }
64 | return nil
65 | }
66 |
67 | func (c *Category) Subcategories() []string {
68 | var r = make([]string, 0, len(c.subcategories))
69 | for _, v := range c.subcategories {
70 | r = append(r, v.ID)
71 | }
72 | return r
73 | }
74 |
75 | func (c *Category) Add(subs ...*Subcategory) {
76 | for _, v := range subs {
77 | v.parent = c
78 | }
79 | c.subcategories = append(c.subcategories, subs...)
80 | }
81 |
82 | func (c *Category) basePath() string {
83 | var loc string
84 | if c.Locale != "" {
85 | loc = "_" + c.Locale
86 | }
87 | return fmt.Sprintf("contents%s/%s", loc, c.ID)
88 | }
89 |
90 | func (c *Category) Path() string {
91 | return fmt.Sprintf("%s/%s%s", c.basePath(), suffixMeta, fileExt)
92 | }
93 |
94 | var catPath = regexp.MustCompile("contents_([a-z]{2})/([^/]+)/.metadata.md")
95 |
96 | func (c *Category) SetPath(filepath string) error {
97 | p := catPath.FindStringSubmatch(filepath)
98 | if len(p) == 0 {
99 | return ErrContent
100 | }
101 | c.Locale = p[1]
102 | c.ID = p[2]
103 | return nil
104 | }
105 |
106 | func (*Category) order() []string { return []string{"Name", "Order"} }
107 | func (*Category) optionals() []string { return nil }
108 | func (c *Category) pointers() args { return args{&c.Name, &c.Order} }
109 | func (c *Category) values() args { return args{c.Name, c.Order} }
110 |
111 | func (c *Category) Contents() string {
112 | return getMeta(c)
113 | }
114 |
115 | func (c *Category) SetContents(contents string) error {
116 | return setMeta(contents, c)
117 | }
118 |
--------------------------------------------------------------------------------
/component/cmp_checklist.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "regexp"
7 | "strings"
8 | )
9 |
10 | type Checklist struct {
11 | parent *Difficulty
12 | Hash string `json:"hash"`
13 | Checks []Check `json:"checks"`
14 | }
15 |
16 | func (c *Checklist) Resource() Resource {
17 | var content = make([]map[string]string, 0, len(c.Checks))
18 | for _, c := range c.Checks {
19 | content = append(content, map[string]string{
20 | "text": c.Text,
21 | })
22 | }
23 | return Resource{
24 | Slug: c.parent.Resource().Slug + "_" + "_checks",
25 | Content: content,
26 | }
27 | }
28 |
29 | type Check struct {
30 | Text string `json:"text"`
31 | NoCheck bool `json:"no_check"`
32 | }
33 |
34 | func (*Check) order() []string { return []string{"Text", "NoCheck"} }
35 | func (*Check) optionals() []string { return nil }
36 | func (c *Check) pointers() args { return args{&c.Text, &c.NoCheck} }
37 | func (c *Check) values() args { return args{c.Text, c.NoCheck} }
38 |
39 | func (c *Checklist) SetParent(d *Difficulty) {
40 | c.parent = d
41 | }
42 |
43 | func (c *Checklist) HasChildren() bool {
44 | return len(c.Checks) != 0
45 | }
46 |
47 | func (c *Checklist) SHA() string {
48 | return c.Hash
49 | }
50 |
51 | func (c *Checklist) Path() string {
52 | return fmt.Sprintf("%s/.checks%s", c.parent.basePath(), fileExt)
53 | }
54 |
55 | var checklistPath = regexp.MustCompile("contents(?:_[a-z]{2})?/[^/]+/[^/]+/[^/]+/.checks.md")
56 |
57 | func (*Checklist) SetPath(filepath string) error {
58 | p := checklistPath.FindString(filepath)
59 | if len(p) == 0 {
60 | return ErrContent
61 | }
62 | return nil
63 | }
64 |
65 | func (c *Checklist) Contents() string {
66 | b := bytes.NewBuffer(nil)
67 | for i := range c.Checks {
68 | if i != 0 {
69 | fmt.Fprint(b, bodySeparator)
70 | }
71 | fmt.Fprint(b, getMeta(&c.Checks[i]))
72 | }
73 | return b.String()
74 | }
75 |
76 | func (c *Checklist) SetContents(contents string) error {
77 | if contents == "" {
78 | if c.Checks != nil {
79 | c.Checks = c.Checks[:0]
80 | }
81 | return nil
82 | }
83 | parts := strings.Split(contents, bodySeparator)
84 | var checks = make([]Check, len(parts))
85 | for i, v := range parts {
86 | if err := setMeta(v, &checks[i]); err != nil {
87 | return err
88 | }
89 | }
90 | c.Checks = checks
91 | return nil
92 | }
93 |
94 | func (c *Checklist) Add(v ...Check) { c.Checks = append(c.Checks, v...) }
95 |
--------------------------------------------------------------------------------
/component/cmp_difficulty.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "regexp"
7 | )
8 |
9 | type Difficulty struct {
10 | parent *Subcategory
11 | ID string `json:"id"`
12 | Descr string `json:"description"`
13 | Hash string `json:"hash"`
14 | items []*Item
15 | checklist *Checklist
16 | }
17 |
18 | func (d *Difficulty) Resource() Resource {
19 | return Resource{
20 | Slug: d.parent.Resource().Slug + "_" + d.ID,
21 | Content: []map[string]string{
22 | map[string]string{"description": d.Descr},
23 | },
24 | }
25 | }
26 |
27 | func (d *Difficulty) HasChildren() bool {
28 | return len(d.items) != 0
29 | }
30 |
31 | func (d *Difficulty) Tree(html bool) interface{} {
32 | var items = make([]Item, len(d.items))
33 | for i, v := range d.items {
34 | items[i] = *v
35 | if html {
36 | items[i].Body = items[i].htmlBody
37 | }
38 | }
39 | return map[string]interface{}{
40 | "id": d.ID,
41 | "description": d.Descr,
42 | "items": items,
43 | "checks": d.checklist.Checks,
44 | }
45 | }
46 |
47 | func (d *Difficulty) SHA() string {
48 | return d.Hash
49 | }
50 |
51 | func (d *Difficulty) SetParent(s *Subcategory) {
52 | d.parent = s
53 | }
54 |
55 | func (d *Difficulty) MarshalJSON() ([]byte, error) {
56 | var m = map[string]interface{}{
57 | "description": d.Descr,
58 | "items": d.ItemNames(),
59 | "checks": d.checklist.Checks,
60 | }
61 | if d.Hash != "" {
62 | m["hash"] = d.Hash
63 | }
64 | return json.Marshal(m)
65 | }
66 |
67 | func (d *Difficulty) Items() []Item {
68 | var dst = make([]Item, len(d.items))
69 | for i, v := range d.items {
70 | dst[i] = *v
71 | }
72 | return dst
73 | }
74 |
75 | func (d *Difficulty) ItemNames() []string {
76 | var r = make([]string, 0, len(d.items))
77 | for i := range d.items {
78 | r = append(r, d.items[i].ID)
79 | }
80 | return r
81 | }
82 |
83 | func (d *Difficulty) Checks() *Checklist {
84 | var dst []Check
85 | if d.checklist == nil {
86 | d.SetChecks(new(Checklist))
87 | }
88 | dst = make([]Check, len(d.checklist.Checks))
89 | for i, v := range d.checklist.Checks {
90 | dst[i] = v
91 | }
92 | return &Checklist{
93 | parent: d,
94 | Hash: d.checklist.Hash,
95 | Checks: dst,
96 | }
97 | }
98 |
99 | func (d *Difficulty) AddChecks(c ...Check) {
100 | if d.checklist == nil {
101 | d.SetChecks(new(Checklist))
102 | }
103 | d.checklist.Add(c...)
104 | }
105 |
106 | func (d *Difficulty) SetChecks(c *Checklist) {
107 | d.checklist = c
108 | c.parent = d
109 | }
110 |
111 | func (d *Difficulty) AddItem(items ...*Item) error {
112 | for _, v := range items {
113 | if d.Item(v.ID) != nil {
114 | return fmt.Errorf("item %s exists in %s/%s", v.ID, d.parent.ID, d.ID)
115 | }
116 | v.parent = d
117 | }
118 | d.items = append(d.items, items...)
119 | return nil
120 | }
121 |
122 | func (d *Difficulty) Item(id string) *Item {
123 | for _, v := range d.items {
124 | if v.ID == id {
125 | return v
126 | }
127 | }
128 | return nil
129 | }
130 |
131 | func (d *Difficulty) basePath() string {
132 | return fmt.Sprintf("%s/%s", d.parent.basePath(), d.ID)
133 | }
134 |
135 | func (d *Difficulty) Path() string {
136 | return fmt.Sprintf("%s/.metadata%s", d.basePath(), fileExt)
137 | }
138 |
139 | var diffPath = regexp.MustCompile("contents(?:_[a-z]{2})?/[^/]+/[^/]+/([^/]+)/.metadata.md")
140 |
141 | func (d *Difficulty) SetPath(filepath string) error {
142 | p := diffPath.FindStringSubmatch(filepath)
143 | if len(p) == 0 {
144 | return ErrContent
145 | }
146 | d.ID = p[1]
147 | return nil
148 | }
149 |
150 | func (*Difficulty) order() []string { return []string{"Description"} }
151 | func (*Difficulty) optionals() []string { return nil }
152 | func (d *Difficulty) pointers() args { return args{&d.Descr} }
153 | func (d *Difficulty) values() args { return args{d.Descr} }
154 |
155 | func (d *Difficulty) Contents() string { return getMeta(d) }
156 |
157 | func (d *Difficulty) SetContents(contents string) error {
158 | if d.checklist == nil {
159 | d.checklist = new(Checklist)
160 | }
161 | return setMeta(contents, d)
162 | }
163 |
--------------------------------------------------------------------------------
/component/cmp_form.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "regexp"
7 | "strings"
8 | )
9 |
10 | type Form struct {
11 | ID string `json:"id"`
12 | Name string `json:"name"`
13 | Hash string `json:"hash,omitempty"`
14 | Locale string `json:"-"`
15 | Screens []FormScreen `json:"screens,omitempty"`
16 | }
17 |
18 | func (f *Form) Resource() Resource {
19 | contents := []map[string]string{
20 | map[string]string{"form": f.Name},
21 | }
22 | for _, s := range f.Screens {
23 | contents = append(contents, map[string]string{"screen": s.Name})
24 | for _, i := range s.Items {
25 | contents = append(contents, map[string]string{
26 | "label": i.Label,
27 | "hint": i.Hint,
28 | "options": strings.Join(i.Options, ";"),
29 | })
30 | }
31 | }
32 | return Resource{
33 | Slug: "forms___" + f.ID,
34 | Content: contents,
35 | }
36 | }
37 |
38 | func (f *Form) HasChildren() bool { return false }
39 |
40 | func (f *Form) SHA() string { return f.Hash }
41 |
42 | func (f *Form) Path() string {
43 | var loc string
44 | if f.Locale != "" {
45 | loc = "_" + f.Locale
46 | }
47 | return fmt.Sprintf("forms%s/%s%s", loc, f.ID, fileExt)
48 | }
49 |
50 | var formPath = regexp.MustCompile("forms_([a-z]{2})/([^/]+).md")
51 |
52 | func (f *Form) SetPath(filepath string) error {
53 | p := formPath.FindStringSubmatch(filepath)
54 | if len(p) == 0 {
55 | return ErrContent
56 | }
57 | f.Locale = p[1]
58 | f.ID = p[2]
59 | return nil
60 | }
61 |
62 | func (*Form) order() []string { return []string{"Name"} }
63 | func (*Form) optionals() []string { return nil }
64 | func (f *Form) pointers() args { return args{&f.Name} }
65 | func (f *Form) values() args { return args{f.Name} }
66 |
67 | func (f *Form) Contents() string {
68 | b := bytes.NewBuffer(nil)
69 | fmt.Fprint(b, getMeta(f))
70 | for i := range f.Screens {
71 | fmt.Fprint(b, bodySeparator, getMeta(&f.Screens[i]))
72 | for _, v := range f.Screens[i].Items {
73 | fmt.Fprint(b, bodySeparator, getMeta(&v))
74 | }
75 | }
76 | return b.String()
77 | }
78 |
79 | func (f *Form) SetContents(contents string) error {
80 | parts := strings.Split(contents, bodySeparator)
81 | if err := setMeta(parts[0], f); err != nil {
82 | return err
83 | }
84 | screenIndex := -1
85 | for _, p := range parts[1:] {
86 | m := metaRow.FindStringSubmatch(strings.SplitN(p, "\n", 2)[0])
87 | if screenIndex < 0 && (len(m) != 3 || m[1] != "Type" || m[2] != "screen") {
88 | return ErrContent
89 | }
90 | switch m[2] {
91 | case "screen":
92 | var s FormScreen
93 | if err := setMeta(p, &s); err != nil {
94 | return err
95 | }
96 | f.Screens = append(f.Screens, s)
97 | screenIndex++
98 | default:
99 | var i FormInput
100 | if err := setMeta(p, &i); err != nil {
101 | return err
102 | }
103 | f.Screens[screenIndex].Items = append(f.Screens[screenIndex].Items, i)
104 | }
105 |
106 | }
107 | return nil
108 | }
109 |
110 | type FormScreen struct {
111 | Name string `json:"name"`
112 | Items []FormInput `json:"items,omitempty"`
113 | }
114 |
115 | func (*FormScreen) order() []string { return []string{"Type", "Name"} }
116 | func (*FormScreen) optionals() []string { return nil }
117 | func (f *FormScreen) pointers() args { var s string; return args{&s, &f.Name} }
118 | func (f *FormScreen) values() args { return args{"screen", f.Name} }
119 |
120 | type FormInput struct {
121 | Type string `json:"type"`
122 | Name string `json:"name,omitempty"`
123 | Label string `json:"label,omitempty"`
124 | Value []string `json:"value,omitempty"`
125 | Options []string `json:"options,omitempty"`
126 | Hint string `json:"hint,omitempty"`
127 | Lines int `json:"lines,omitempty"`
128 | }
129 |
130 | func (*FormInput) order() []string {
131 | return []string{"Type", "Name", "Label", "Value", "Options", "Hint", "Lines"}
132 | }
133 | func (*FormInput) optionals() []string {
134 | return []string{"Value", "Options", "Hint", "Lines"}
135 | }
136 |
137 | func (f *FormInput) pointers() args {
138 | return args{&f.Type, &f.Name, &f.Label, &f.Value, &f.Options, &f.Hint, &f.Lines}
139 | }
140 | func (f *FormInput) values() args {
141 | return args{f.Type, f.Name, f.Label, f.Value, f.Options, f.Hint, f.Lines}
142 | }
143 |
--------------------------------------------------------------------------------
/component/cmp_item.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | "strings"
7 |
8 | "github.com/russross/blackfriday"
9 | )
10 |
11 | const paragraphSep = "\n\n"
12 |
13 | type Item struct {
14 | parent *Difficulty
15 | ID string `json:"id"`
16 | Hash string `json:"hash,omitempty"`
17 | Title string `json:"title"`
18 | Body string `json:"body"`
19 | htmlBody string
20 | Order float64 `json:"-"`
21 | }
22 |
23 | func (i *Item) Resource() Resource {
24 | parts := strings.Split(i.Body, paragraphSep)
25 | content := make([]map[string]string, len(parts)+1)
26 | content[0] = map[string]string{"title": i.Title}
27 | for i := range parts {
28 | content[i+1] = map[string]string{"body": parts[i]}
29 | }
30 | return Resource{Slug: i.parent.Resource().Slug + "_" + i.ID, Content: []map[string]string{
31 | map[string]string{"title": i.Title, "body": i.Body},
32 | }}
33 | }
34 |
35 | func (i *Item) SetParent(d *Difficulty) {
36 | i.parent = d
37 | }
38 |
39 | func (i *Item) HasChildren() bool {
40 | return false
41 | }
42 |
43 | func (i *Item) SHA() string {
44 | return i.Hash
45 | }
46 |
47 | func (i *Item) Path() string {
48 | return fmt.Sprintf("%s/%s%s", i.parent.basePath(), i.ID, fileExt)
49 | }
50 |
51 | var itemPath = regexp.MustCompile("contents(?:_[a-z]{2})?/[^/]+/[^/]+/[^/]+/([^/]+).md")
52 |
53 | func (i *Item) SetPath(filepath string) error {
54 | p := itemPath.FindStringSubmatch(filepath)
55 | if len(p) == 0 || p[1] == suffixMeta {
56 | return ErrContent
57 | }
58 | i.ID = p[1]
59 | return nil
60 | }
61 |
62 | func (*Item) order() []string { return []string{"Title", "Order"} }
63 | func (*Item) optionals() []string { return nil }
64 | func (i *Item) pointers() args { return args{&i.Title, &i.Order} }
65 | func (i *Item) values() args { return args{i.Title, i.Order} }
66 |
67 | func (i *Item) Contents() string {
68 | return fmt.Sprint(getMeta(i), bodySeparator, i.Body)
69 | }
70 |
71 | func (i *Item) SetContents(contents string) error {
72 | parts := strings.SplitN(strings.Trim(contents, "\n"), bodySeparator, 2)
73 | if len(parts) != 2 {
74 | return ErrContent
75 | }
76 | if err := setMeta(parts[0], i); err != nil {
77 | return err
78 | }
79 | i.Body = parts[1]
80 | i.htmlBody = string(blackfriday.Run([]byte(i.Body)))
81 | return nil
82 | }
83 |
--------------------------------------------------------------------------------
/component/cmp_subcategory.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "regexp"
7 | )
8 |
9 | type Subcategory struct {
10 | parent *Category
11 | ID string `json:"id"`
12 | Name string `json:"name"`
13 | Hash string `json:"hash"`
14 | Order float64 `json:"-"`
15 | difficulties []*Difficulty
16 | }
17 |
18 | func (s *Subcategory) Resource() Resource {
19 | return Resource{
20 | Slug: s.parent.Resource().Slug + "_" + s.ID,
21 | Content: []map[string]string{
22 | map[string]string{"name": s.Name},
23 | },
24 | }
25 | }
26 |
27 | func (s *Subcategory) HasChildren() bool {
28 | return len(s.difficulties) != 0
29 | }
30 |
31 | func (s *Subcategory) Tree(html bool) interface{} {
32 | var difficulties = make([]interface{}, len(s.difficulties))
33 | for i, v := range s.difficulties {
34 | difficulties[i] = v.Tree(html)
35 | }
36 | return map[string]interface{}{
37 | "id": s.ID,
38 | "name": s.Name,
39 | "difficulties": difficulties,
40 | }
41 | }
42 |
43 | func (s *Subcategory) SHA() string {
44 | return s.Hash
45 | }
46 |
47 | func (s *Subcategory) SetParent(c *Category) {
48 | s.parent = c
49 | }
50 |
51 | func (s *Subcategory) MarshalJSON() ([]byte, error) {
52 | var m = map[string]interface{}{
53 | "name": s.Name,
54 | "difficulties": s.DifficultyNames(),
55 | }
56 | if s.Hash != "" {
57 | m["hash"] = s.Hash
58 | }
59 | return json.Marshal(m)
60 | }
61 |
62 | func (s *Subcategory) Difficulties() []Difficulty {
63 | var dst = make([]Difficulty, len(s.difficulties))
64 | for i, v := range s.difficulties {
65 | dst[i] = *v
66 | }
67 | return dst
68 | }
69 |
70 | func (s *Subcategory) DifficultyNames() []string {
71 | var r = make([]string, 0, len(s.difficulties))
72 | for i := range s.difficulties {
73 | r = append(r, s.difficulties[i].ID)
74 | }
75 | return r
76 | }
77 |
78 | func (s *Subcategory) AddDifficulty(difficulties ...*Difficulty) error {
79 | for _, v := range difficulties {
80 | if s.Difficulty(v.ID) != nil {
81 | return fmt.Errorf("Difficulty %s exists in %s/%s", v.ID, s.parent.ID, s.ID)
82 | }
83 | v.parent = s
84 | }
85 | s.difficulties = append(s.difficulties, difficulties...)
86 | return nil
87 | }
88 |
89 | func (s *Subcategory) Difficulty(ID string) *Difficulty {
90 | for _, v := range s.difficulties {
91 | if v.ID == ID {
92 | return v
93 | }
94 | }
95 | return nil
96 | }
97 |
98 | func (s *Subcategory) basePath() string {
99 | return fmt.Sprintf("%s/%s", s.parent.basePath(), s.ID)
100 | }
101 |
102 | func (s *Subcategory) Path() string {
103 | return fmt.Sprintf("%s/.metadata%s", s.basePath(), fileExt)
104 | }
105 |
106 | var subPath = regexp.MustCompile("contents(?:_[a-z]{2})?/[^/]+/([^/]+)/.metadata.md")
107 |
108 | func (s *Subcategory) SetPath(filepath string) error {
109 | p := subPath.FindStringSubmatch(filepath)
110 | if len(p) == 0 {
111 | return ErrContent
112 | }
113 | s.ID = p[1]
114 | return nil
115 | }
116 |
117 | func (*Subcategory) order() []string { return []string{"Name", "Order"} }
118 | func (*Subcategory) optionals() []string { return nil }
119 | func (s *Subcategory) pointers() args { return args{&s.Name, &s.Order} }
120 | func (s *Subcategory) values() args { return args{s.Name, s.Order} }
121 |
122 | func (s *Subcategory) Contents() string { return getMeta(s) }
123 |
124 | func (s *Subcategory) SetContents(contents string) error {
125 | return setMeta(contents, s)
126 | }
127 |
--------------------------------------------------------------------------------
/component/common.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "path/filepath"
7 | "strings"
8 | )
9 |
10 | const (
11 | actionCreate = iota
12 | actionUpdate
13 | actionDelete
14 | )
15 |
16 | var commitMsg = map[int]string{
17 | actionCreate: "Create",
18 | actionUpdate: "Update",
19 | actionDelete: "Delete",
20 | }
21 |
22 | var (
23 | ErrContent = errors.New("Invalid content")
24 | ErrSlug = errors.New("Invalid Slug")
25 | )
26 |
27 | const (
28 | bodySeparator = "\n\n"
29 | suffixMeta = ".metadata"
30 | suffixChecks = ".checks"
31 | fileExt = ".md"
32 | )
33 |
34 | // A Component is en element of the resource tree
35 | type Component interface {
36 | Path() string
37 | Contents() string
38 | SetPath(path string) error
39 | SetContents(contents string) error
40 | SHA() string
41 | HasChildren() bool
42 | Resource() Resource
43 | }
44 |
45 | type Resource struct {
46 | Slug string
47 | Content []map[string]string
48 | }
49 |
50 | func newCmp(path string) (Component, error) {
51 | p := strings.Split(path, "/")
52 | switch l := len(p); l {
53 | case 2:
54 | if formPath.MatchString(path) {
55 | return new(Form), nil
56 | }
57 | if p[0] == "assets" && isImage(p[1]) {
58 | return new(Asset), nil
59 | }
60 | case 3:
61 | if strings.TrimSuffix(p[2], fileExt) == suffixMeta {
62 | return new(Category), nil
63 | }
64 | case 4:
65 | if strings.TrimSuffix(p[3], fileExt) == suffixMeta {
66 | return new(Subcategory), nil
67 | }
68 | case 5:
69 | switch strings.TrimSuffix(p[4], fileExt) {
70 | case suffixMeta:
71 | return new(Difficulty), nil
72 | case suffixChecks:
73 | return new(Checklist), nil
74 | default:
75 | if isMd(p[4]) {
76 | return new(Item), nil
77 | }
78 | }
79 | }
80 | return nil, ErrContent
81 | }
82 |
83 | func filterCat(name string) bool {
84 | return strings.HasSuffix(name, suffixMeta+fileExt)
85 | }
86 |
87 | func filterRes(name string) bool {
88 | if !strings.HasSuffix(name, fileExt) {
89 | return isImage(name)
90 | }
91 | return !strings.HasSuffix(name, suffixMeta+fileExt)
92 | }
93 |
94 | func isMd(name string) bool { return filepath.Ext(name) == fileExt }
95 |
96 | func isImage(name string) bool {
97 | ext := filepath.Ext(name)
98 | for _, v := range []string{".jpg", ".jpeg", ".gif", ".png", ".bmp"} {
99 | if v == ext {
100 | return true
101 | }
102 | }
103 | return false
104 | }
105 |
106 | type parseError struct {
107 | file string
108 | phase string
109 | err interface{}
110 | }
111 |
112 | func (p parseError) Error() string { return fmt.Sprintf("[%s]%s - %v", p.phase, p.file, p.err) }
113 |
114 | func strPtr(s string) *string { return &s }
115 |
116 | func repoAddress(owner, name string) string {
117 | return fmt.Sprintf("https://github.com/%s/%s", owner, name)
118 | }
119 |
120 | func uploadAddress(owner, name, file string) string {
121 | return fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s", owner, name, file)
122 | }
123 |
--------------------------------------------------------------------------------
/component/meta.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "regexp"
7 | "strconv"
8 | "strings"
9 | )
10 |
11 | type meta interface {
12 | order() []string
13 | optionals() []string
14 | pointers() args
15 | values() args
16 | }
17 |
18 | var metaRow = regexp.MustCompile(`\[([a-zA-Z]+)\]: # \((.*)\)`)
19 |
20 | type args []interface{}
21 |
22 | func setMeta(meta string, m meta) error {
23 | order, pointers, optionals := m.order(), m.pointers(), m.optionals()
24 | rows := strings.Split(meta, "\n")
25 | if len(rows) < len(order)-len(optionals) {
26 | return fmt.Errorf("Expected %v-%v, got %v", len(order)-len(optionals), len(order), len(rows))
27 | }
28 | for i, row := range rows {
29 | m := metaRow.FindStringSubmatch(row)
30 | if len(m) != 3 {
31 | return fmt.Errorf("Invalid %q", row)
32 | }
33 | for {
34 | if m[1] == order[i] {
35 | if len(optionals) > 0 && order[i] == optionals[0] {
36 | optionals = optionals[1:]
37 | }
38 | if err := setMetaValue(pointers[i], m[2]); err != nil {
39 | return fmt.Errorf("meta: %s", err.Error())
40 | }
41 | break
42 | }
43 | if len(optionals) == 0 || order[i] != optionals[0] {
44 | return fmt.Errorf("Expected %v, got %v", order[i], optionals[0])
45 | }
46 | optionals = optionals[1:]
47 | pointers = pointers[:i+copy(pointers[i:], pointers[i+1:])]
48 | order = order[:i+copy(order[i:], order[i+1:])]
49 | }
50 | }
51 | return nil
52 | }
53 |
54 | func setMetaValue(p interface{}, v string) error {
55 | switch pointer := p.(type) {
56 | case *string:
57 | *pointer = v
58 | case *bool:
59 | *pointer = v == "true"
60 | case *int:
61 | if v == "" {
62 | return nil
63 | }
64 | n, err := strconv.Atoi(v)
65 | if err != nil {
66 | return fmt.Errorf("Invalid int: %v", v)
67 | }
68 | *pointer = n
69 | case *float64:
70 | n, err := strconv.ParseFloat(v, 64)
71 | if err != nil {
72 | return fmt.Errorf("Invalid float: %v", v)
73 | }
74 | *pointer = n
75 | case *[]string:
76 | if strings.TrimSpace(v) == "" {
77 | return nil
78 | }
79 | *pointer = strings.Split(v, ";")
80 | default:
81 | return fmt.Errorf("unknown type %T", pointer)
82 | }
83 | return nil
84 | }
85 |
86 | func getMeta(m meta) string {
87 | order, optionals := m.order(), m.optionals()
88 | b := bytes.NewBuffer(nil)
89 | for i, v := range m.values() {
90 | var isZero bool
91 | switch t := v.(type) {
92 | case string:
93 | isZero = t == ""
94 | case int, float64:
95 | isZero = t == 0
96 | case bool:
97 | isZero = t
98 | case []string:
99 | isZero = len(t) == 0 || len(t) == 1 && t[0] == ""
100 | v = strings.Join(t, ";")
101 | }
102 | if len(optionals) != 0 && order[i] == optionals[0] {
103 | optionals = optionals[1:]
104 | if isZero {
105 | continue
106 | }
107 | }
108 | if i > 0 {
109 | b.WriteRune('\n')
110 | }
111 | fmt.Fprintf(b, "[%s]: # (%v)", order[i], v)
112 | }
113 | return b.String()
114 | }
115 |
--------------------------------------------------------------------------------
/component/meta_test.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "reflect"
5 | "strings"
6 | "testing"
7 | )
8 |
9 | func TestMeta(t *testing.T) {
10 | var testCases = []struct {
11 | meta string
12 | result *FormInput
13 | }{
14 | {"[Type]: # (text_input)", nil},
15 | {"[Type]: # (text_input)\n[Name]: # (name)", nil},
16 | {"[Type]: # (text_input)\n[Label]: # (Name:)", nil},
17 | {"[Type]: # (text_input)\n[Name]: # (name)\n[Label]: # (Name:)", &FormInput{
18 | Type: "text_input", Name: "name", Label: "Name:",
19 | }},
20 | {"[Type]: # (text_input)\n[Name]: # (name)\n[Label]: # (Name:)\n[Value]: # (some)\n[Hint]: # (hint)\n[Lines]: # (10)", &FormInput{
21 | Type: "text_input", Name: "name", Label: "Name:", Value: []string{"some"}, Hint: "hint", Lines: 10,
22 | }},
23 | {"[Type]: # (text_input)\n[Name]: # (name)\n[Label]: # (Name:)\n[Value]: # (some)\n[Options]: # (a;b)\n[Hint]: # (hint)\n[Lines]: # (10)", &FormInput{
24 | Type: "text_input", Name: "name", Label: "Name:", Value: []string{"some"}, Options: []string{"a", "b"}, Hint: "hint", Lines: 10,
25 | }},
26 | }
27 | for _, tc := range testCases {
28 | f := FormInput{}
29 | if err := setMeta(tc.meta, &f); err != nil {
30 | if tc.result != nil {
31 | t.Error("expected ok, got error")
32 | }
33 | continue
34 | }
35 | if tc.result == nil {
36 | t.Error("expected error, got ok")
37 | continue
38 | }
39 | if !reflect.DeepEqual(&f, tc.result) {
40 | t.Error("expected", tc.result, " got", &f)
41 | }
42 | meta := getMeta(&f)
43 | if meta != tc.meta {
44 | t.Errorf("expected \n%q, got \n%q", tc.meta, meta)
45 | }
46 | }
47 | }
48 |
49 | func TestGetMeta(t *testing.T) {
50 | var base = FormInput{
51 | Type: "a",
52 | Name: "b",
53 | Label: "c",
54 | Value: []string{"d"},
55 | Options: []string{"e"},
56 | Hint: "f",
57 | Lines: 1,
58 | }
59 |
60 | var testCases = []struct {
61 | input func(FormInput) FormInput
62 | lines int
63 | }{
64 | {func(f FormInput) FormInput {
65 | return f
66 | }, 7},
67 | {func(f FormInput) FormInput {
68 | f.Value = nil
69 | return f
70 | }, 6},
71 | {func(f FormInput) FormInput {
72 | f.Value = nil
73 | f.Options = nil
74 | return f
75 | }, 5},
76 | {func(f FormInput) FormInput {
77 | f.Value = nil
78 | f.Options = nil
79 | f.Hint = ""
80 | return f
81 | }, 4},
82 | {func(f FormInput) FormInput {
83 | f.Value = nil
84 | f.Options = nil
85 | f.Hint = ""
86 | f.Lines = 0
87 | return f
88 | }, 3},
89 | {func(f FormInput) FormInput {
90 | f.Hint = ""
91 | return f
92 | }, 6},
93 | }
94 |
95 | for _, tc := range testCases {
96 | f := tc.input(base)
97 | meta := strings.Split(getMeta(&f), "\n")
98 | if l := len(meta); l != tc.lines {
99 | t.Errorf("Expected %d lines, got %d\n%q", tc.lines, l, meta)
100 | }
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/component/parser.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "io"
5 | "sort"
6 | "strings"
7 |
8 | "gopkg.in/src-d/go-git.v4/plumbing/object"
9 | )
10 |
11 | // Parser is an helper, creates a tree from the repo
12 | type Parser struct {
13 | index map[[2]string]int
14 | categories []*Category
15 | assets []*Asset
16 | forms []*Form
17 | }
18 |
19 | // Parse executes the parsing on a repo
20 | func (p *Parser) Parse(t *object.Tree) error {
21 | p.index = make(map[[2]string]int)
22 | p.categories = make([]*Category, 0)
23 | if err := p.parse(t, filterCat); err != nil {
24 | return err
25 | }
26 | if err := p.parse(t, filterRes); err != nil {
27 | return err
28 | }
29 | sort.Sort(catSorter(p.categories))
30 | for i := range p.categories {
31 | sort.Sort(subSorter(p.categories[i].subcategories))
32 | for j := range p.categories[i].subcategories {
33 | for k := range p.categories[i].subcategories[j].difficulties {
34 | sort.Sort(itemSorter(p.categories[i].subcategories[j].difficulties[k].items))
35 | }
36 | }
37 | }
38 | return nil
39 | }
40 |
41 | func (p *Parser) parse(t *object.Tree, fn func(name string) bool) error {
42 | for iter := t.Files(); ; {
43 | f, err := iter.Next()
44 | if err != nil {
45 | if err == io.EOF {
46 | break
47 | }
48 | return err
49 | }
50 | if !fn(f.Name) {
51 | continue
52 | }
53 | if err := p.parseFile(f); err != nil {
54 | return err
55 | }
56 | }
57 | return nil
58 | }
59 |
60 | func (p *Parser) parseFile(f *object.File) error {
61 | contents, err := f.Contents()
62 | if err != nil {
63 | return parseError{f.Name, "read", err}
64 | }
65 | if ok, _ := f.IsBinary(); !ok {
66 | contents = strings.Replace(strings.TrimSpace(contents), "\r\n", "\n", -1)
67 | }
68 | cmp, err := newCmp(f.Name)
69 | if err != nil {
70 | return parseError{f.Name, "cmp", err}
71 | }
72 | if err := p.setPath(f.Name, cmp); err != nil {
73 | return err
74 | }
75 | if err := cmp.SetContents(contents); err != nil {
76 | return parseError{f.Name, "contents", err}
77 | }
78 | return nil
79 | }
80 |
81 | func (p *Parser) setPath(name string, cmp Component) error {
82 | if err := cmp.SetPath(name); err != nil {
83 | return parseError{name, "path", err}
84 | }
85 | switch c := cmp.(type) {
86 | case *Asset:
87 | p.assets = append(p.assets, c)
88 | return nil
89 | case *Form:
90 | p.forms = append(p.forms, c)
91 | return nil
92 | }
93 |
94 | parts := strings.Split(name, "/")
95 | idx := [2]string{parts[1], name[9:11]}
96 | if cat, ok := cmp.(*Category); ok {
97 | p.index[idx] = len(p.categories)
98 | p.categories = append(p.categories, cat)
99 | return nil
100 | }
101 | cat := p.categories[p.index[idx]]
102 | if cat == nil {
103 | return parseError{name, "path", "Invalid cat"}
104 | }
105 |
106 | if sub, ok := cmp.(*Subcategory); ok {
107 | cat.Add(sub)
108 | return nil
109 | }
110 | sub := cat.Sub(parts[2])
111 | if sub == nil {
112 | sub = &Subcategory{ID: parts[2]}
113 | cat.Add(sub)
114 | }
115 |
116 | if dif, ok := cmp.(*Difficulty); ok {
117 | sub.AddDifficulty(dif)
118 | return nil
119 | }
120 | dif := sub.Difficulty(parts[3])
121 | if dif == nil {
122 | dif = &Difficulty{ID: parts[3]}
123 | sub.AddDifficulty(dif)
124 | }
125 |
126 | switch c := cmp.(type) {
127 | case *Item:
128 | dif.AddItem(c)
129 | case *Checklist:
130 | dif.SetChecks(c)
131 | default:
132 | return parseError{name, "type", "Invalid Path"}
133 | }
134 | return nil
135 | }
136 |
137 | func (p *Parser) Categories() map[string][]*Category {
138 | var res = make(map[string][]*Category)
139 | for _, cat := range p.categories {
140 | res[cat.Locale] = append(res[cat.Locale], cat)
141 | }
142 | return res
143 | }
144 |
145 | func (p *Parser) Assets() []*Asset {
146 | return p.assets
147 | }
148 |
149 | func (p *Parser) Forms() []*Form {
150 | return p.forms
151 | }
152 |
--------------------------------------------------------------------------------
/component/resource_parser.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "fmt"
7 | "strings"
8 | )
9 |
10 | func splitSlug(s string) []string {
11 | s = strings.Replace(s, "_", "|", -1)
12 | s = strings.Replace(s, "|||", "|_|", -1)
13 | return strings.Split(s, "|")
14 | }
15 |
16 | func NewResourceParser() *ResourceParser {
17 | return &ResourceParser{
18 | categories: make(map[string][]*Category),
19 | forms: make(map[string][]*Form),
20 | }
21 | }
22 |
23 | type ResourceParser struct {
24 | buffer bytes.Buffer
25 | categories map[string][]*Category
26 | forms map[string][]*Form
27 | }
28 |
29 | func (r *ResourceParser) Categories() map[string][]*Category { return r.categories }
30 |
31 | func (r *ResourceParser) Parse(cmp Component, res *Resource, locale string) error {
32 | switch v := cmp.(type) {
33 | case *Form:
34 | return r.parseForm(v, res, locale)
35 | case *Category:
36 | return r.parseCategory(v, res, locale)
37 | case *Subcategory:
38 | return r.parseSubcategory(v, res, locale)
39 | case *Difficulty:
40 | return r.parseDifficulty(v, res, locale)
41 | case *Item:
42 | return r.parseItem(v, res, locale)
43 | case *Checklist:
44 | return r.parseChecklist(v, res, locale)
45 | default:
46 | return errors.New("Invalid Component")
47 | }
48 | }
49 |
50 | func (r *ResourceParser) parseForm(f *Form, res *Resource, locale string) error {
51 | var newForm = Form{
52 | ID: f.ID,
53 | Name: res.Content[0]["form"],
54 | Locale: locale,
55 | Screens: make([]FormScreen, len(f.Screens)),
56 | }
57 | m := res.Content[1:]
58 | for i := range newForm.Screens {
59 | screen := &newForm.Screens[i]
60 | screen.Items = make([]FormInput, len(f.Screens[i].Items))
61 | if f.Screens[i].Name != "" {
62 | if len(m) == 0 {
63 | return fmt.Errorf("No more at screen %d/%d", i+1, len(f.Screens))
64 | }
65 | if name := m[0]["screen"]; name != "" {
66 | screen.Name = name
67 | m = m[1:]
68 | } else {
69 | return fmt.Errorf("Expected screen %d, got item", i)
70 | }
71 | }
72 | for j := range screen.Items {
73 | item := screen.Items[j]
74 | if item.Label == "" && item.Hint == "" && item.Options == nil {
75 | continue
76 | }
77 | if s := m[0]["screen"]; s != "" {
78 | return fmt.Errorf("Expected item %d/%d, got screen %q", i, j, s)
79 | }
80 | item.Label, item.Hint = m[0]["label"], m[0]["hint"]
81 | item.Options = strings.Split(m[0]["options"], ";")
82 | m = m[1:]
83 | }
84 | }
85 | r.forms[newForm.Locale] = append(r.forms[newForm.Locale], &newForm)
86 | return nil
87 | }
88 |
89 | func (r *ResourceParser) getCategory(cat *Category, locale string) *Category {
90 | for _, c := range r.categories[locale] {
91 | if c.ID == cat.ID {
92 | return c
93 | }
94 | }
95 | c := Category{ID: cat.ID, Order: cat.Order, Locale: locale}
96 | r.categories[locale] = append(r.categories[locale], &c)
97 | return &c
98 | }
99 |
100 | func (r *ResourceParser) parseCategory(c *Category, res *Resource, locale string) error {
101 | if len(res.Content) != 1 {
102 | return ErrContent
103 | }
104 | if cat := r.getCategory(c, locale); cat != nil {
105 | cat.Name = res.Content[0]["name"]
106 | return nil
107 | }
108 | r.categories[locale] = append(r.categories[locale], &Category{
109 | ID: c.ID,
110 | Order: c.Order,
111 | Name: res.Content[0]["name"],
112 | Locale: locale,
113 | })
114 | return nil
115 | }
116 |
117 | func (r *ResourceParser) getSubcategory(sub *Subcategory, locale string) *Subcategory {
118 | cat := r.getCategory(sub.parent, locale)
119 | for _, s := range cat.subcategories {
120 | if s.ID == sub.ID {
121 | return s
122 | }
123 | }
124 | s := Subcategory{ID: sub.ID, Order: sub.Order}
125 | cat.Add(&s)
126 | return &s
127 | }
128 |
129 | func (r *ResourceParser) parseSubcategory(s *Subcategory, res *Resource, locale string) error {
130 | if len(res.Content) != 1 {
131 | return ErrContent
132 | }
133 | sub := r.getSubcategory(s, locale)
134 | sub.Name = res.Content[0]["name"]
135 | return nil
136 | }
137 |
138 | func (r *ResourceParser) getDifficulty(diff *Difficulty, locale string) *Difficulty {
139 | sub := r.getSubcategory(diff.parent, locale)
140 | for _, d := range sub.difficulties {
141 | if d.ID == diff.ID {
142 | return d
143 | }
144 | }
145 | d := Difficulty{ID: diff.ID}
146 | sub.AddDifficulty(&d)
147 | return &d
148 | }
149 |
150 | func (r *ResourceParser) parseDifficulty(d *Difficulty, res *Resource, locale string) error {
151 | if len(res.Content) != 1 {
152 | return ErrContent
153 | }
154 | diff := r.getDifficulty(d, locale)
155 | diff.Descr = res.Content[0]["description"]
156 | return nil
157 | }
158 |
159 | func (r *ResourceParser) parseItem(i *Item, res *Resource, locale string) error {
160 | if len(res.Content) == 0 {
161 | return ErrContent
162 | }
163 | item := &Item{
164 | ID: i.ID,
165 | Title: strings.TrimSpace(res.Content[0]["title"]),
166 | Order: i.Order,
167 | }
168 | r.buffer.Reset()
169 | // Old Verion Compatibility
170 | if res.Content[0]["body"] != "" {
171 | if len(res.Content) != 1 {
172 | return fmt.Errorf("Invalid Legacy %q (%s)", i.parent.ID, locale)
173 | }
174 | r.buffer.WriteString(strings.TrimSpace(res.Content[0]["body"]))
175 | } else {
176 | for _, v := range res.Content[1:] {
177 | if r.buffer.Len() != 0 {
178 | r.buffer.WriteString(paragraphSep)
179 | }
180 | r.buffer.WriteString(strings.TrimSpace(v["body"]))
181 | }
182 | }
183 | item.Body = r.buffer.String()
184 | r.getDifficulty(i.parent, locale).AddItem(item)
185 | return nil
186 | }
187 |
188 | func (r *ResourceParser) parseChecklist(c *Checklist, res *Resource, locale string) error {
189 | for len(res.Content) > 0 && res.Content[0] == nil {
190 | res.Content = res.Content[1:]
191 | }
192 | if l, e := len(res.Content), len(c.Checks); l != e {
193 | return fmt.Errorf("%d checks, %d expected", l, e)
194 | }
195 |
196 | var checks Checklist
197 | for i, r := range res.Content {
198 | checks.Add(Check{
199 | Text: strings.TrimSpace(r["text"]),
200 | NoCheck: c.Checks[i].NoCheck,
201 | })
202 | }
203 | r.getDifficulty(c.parent, locale).SetChecks(&checks)
204 | return nil
205 | }
206 |
--------------------------------------------------------------------------------
/component/resource_parser_test.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | import (
4 | . "gopkg.in/check.v1"
5 | )
6 |
7 | func (CmpSuite) TestParseResource(c *C) {
8 | p := NewResourceParser()
9 | var err error
10 |
11 | catCmp := Category{ID: "cat", Locale: "en", Name: "Test Category"}
12 | catRes := Resource{
13 | Slug: "cat",
14 | Content: []map[string]string{map[string]string{"name": "Categoria di prova"}},
15 | }
16 | err = p.Parse(&catCmp, &catRes, "it")
17 | c.Assert(err, IsNil)
18 |
19 | subCmp := Subcategory{ID: "sub", Name: "Test Sub", parent: &catCmp}
20 | subRes := Resource{
21 | Slug: "cat___sub",
22 | Content: []map[string]string{map[string]string{"name": "Sub di prova"}},
23 | }
24 | err = p.Parse(&subCmp, &subRes, "it")
25 | c.Assert(err, IsNil)
26 |
27 | difCmp := Difficulty{ID: "dif", Descr: "Test dif", parent: &subCmp}
28 | difRes := Resource{
29 | Slug: "cat___sub___dif",
30 | Content: []map[string]string{map[string]string{"name": "dif di prova"}},
31 | }
32 | err = p.Parse(&difCmp, &difRes, "it")
33 | c.Assert(err, IsNil)
34 |
35 | itemCmp := Item{ID: "item", Title: "Test item", parent: &difCmp, Body: "row1\n\nrow2\n\nrow3"}
36 | itemRes := Resource{
37 | Slug: "cat___sub___dif___item",
38 | Content: []map[string]string{
39 | map[string]string{"title": "item di prova"},
40 | map[string]string{"body": "riga1"},
41 | map[string]string{"body": "riga2"},
42 | map[string]string{"body": "riga3"},
43 | },
44 | }
45 | err = p.Parse(&itemCmp, &itemRes, "it")
46 | c.Assert(err, IsNil)
47 |
48 | legacyCmp := Item{ID: "item-legacy", Title: "Old Test item", parent: &difCmp, Body: "row1\n\nrow2\n\nrow3"}
49 | legacyRes := Resource{
50 | Slug: "cat___sub___dif____item-legacy",
51 | Content: []map[string]string{
52 | map[string]string{"title": "item di prova legacy", "body": "riga1\n\nriga2\n\nriga3"},
53 | },
54 | }
55 | err = p.Parse(&legacyCmp, &legacyRes, "it")
56 | c.Assert(err, IsNil)
57 |
58 | legacyRes.Content = append(legacyRes.Content, map[string]string{"body": "moar"})
59 | err = p.Parse(&legacyCmp, &legacyRes, "it")
60 | c.Assert(err, NotNil)
61 | }
62 |
--------------------------------------------------------------------------------
/component/sort.go:
--------------------------------------------------------------------------------
1 | package component
2 |
3 | type catSorter []*Category
4 |
5 | func (s catSorter) Len() int { return len(s) }
6 | func (s catSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
7 | func (s catSorter) Less(i, j int) bool { return s[i].Order < s[j].Order }
8 |
9 | type subSorter []*Subcategory
10 |
11 | func (s subSorter) Len() int { return len(s) }
12 | func (s subSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
13 | func (s subSorter) Less(i, j int) bool { return s[i].Order < s[j].Order }
14 |
15 | type itemSorter []*Item
16 |
17 | func (s itemSorter) Len() int { return len(s) }
18 | func (s itemSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
19 | func (s itemSorter) Less(i, j int) bool { return s[i].Order < s[j].Order }
20 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/securityfirst/tent
2 |
3 | require (
4 | github.com/BurntSushi/toml v0.3.1 // indirect
5 | github.com/gin-contrib/sse v0.0.0-20190125020943-a7658810eb74 // indirect
6 | github.com/gin-gonic/gin v1.3.0
7 | github.com/google/go-github v17.0.0+incompatible
8 | github.com/google/go-querystring v1.0.0 // indirect
9 | github.com/inconshreveable/mousetrap v1.0.0 // indirect
10 | github.com/json-iterator/go v1.1.5 // indirect
11 | github.com/mattn/go-isatty v0.0.4 // indirect
12 | github.com/mattn/go-runewidth v0.0.4 // indirect
13 | github.com/mattn/godown v0.0.0-20180312012330-2e9e17e0ea51
14 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
15 | github.com/modern-go/reflect2 v1.0.1 // indirect
16 | github.com/russross/blackfriday v2.0.0+incompatible
17 | github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
18 | github.com/spf13/cobra v0.0.3
19 | github.com/spf13/viper v1.3.1
20 | github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43 // indirect
21 | golang.org/x/oauth2 v0.0.0-20190211225200-5f6b76b7c9dd
22 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127
23 | gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
24 | gopkg.in/go-playground/validator.v8 v8.18.2 // indirect
25 | gopkg.in/src-d/go-git.v4 v4.9.1
26 | )
27 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
3 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
4 | github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs=
5 | github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs=
6 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA=
7 | github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
8 | github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
9 | github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
10 | github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
11 | github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
12 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
13 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
14 | github.com/emirpasic/gods v1.9.0 h1:rUF4PuzEjMChMiNsVjdI+SyLu7rEqpQ5reNFnhC7oFo=
15 | github.com/emirpasic/gods v1.9.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o=
16 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
17 | github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
18 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
19 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
20 | github.com/gin-contrib/sse v0.0.0-20190125020943-a7658810eb74 h1:FaI7wNyesdMBSkIRVUuEEYEvmzufs7EqQvRAxfEXGbQ=
21 | github.com/gin-contrib/sse v0.0.0-20190125020943-a7658810eb74/go.mod h1:VJ0WA2NBN22VlZ2dKZQPAPnyWw5XTlK1KymzLKsr59s=
22 | github.com/gin-gonic/gin v1.3.0 h1:kCmZyPklC0gVdL728E6Aj20uYBJV93nj/TkwBTKhFbs=
23 | github.com/gin-gonic/gin v1.3.0/go.mod h1:7cKuhb5qV2ggCFctp2fJQ+ErvciLZrIeoOSOm6mUr7Y=
24 | github.com/gliderlabs/ssh v0.1.1 h1:j3L6gSLQalDETeEg/Jg0mGY0/y/N6zI2xX1978P0Uqw=
25 | github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0=
26 | github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
27 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
28 | github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
29 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
30 | github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
31 | github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
32 | github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
33 | github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
34 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
35 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
36 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
37 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
38 | github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
39 | github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
40 | github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
41 | github.com/json-iterator/go v1.1.5 h1:gL2yXlmiIo4+t+y32d4WGwOjKGYcGOuyrg46vadswDE=
42 | github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
43 | github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e h1:RgQk53JHp/Cjunrr1WlsXSZpqXn+uREuHvUVcK82CV8=
44 | github.com/kevinburke/ssh_config v0.0.0-20180830205328-81db2a75821e/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
45 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
46 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
47 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
48 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
49 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
50 | github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
51 | github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
52 | github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs=
53 | github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
54 | github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
55 | github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
56 | github.com/mattn/godown v0.0.0-20180312012330-2e9e17e0ea51 h1:MpI7hy3MiCnrggmZI/s8LaPbLVOOWpzDbjA4F+XaXaM=
57 | github.com/mattn/godown v0.0.0-20180312012330-2e9e17e0ea51/go.mod h1:s3KUdOIXJ+jaGM++XHiXA6gikdleaWVATCcQGD4h734=
58 | github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
59 | github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
60 | github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
61 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
62 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
63 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
64 | github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
65 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
66 | github.com/pelletier/go-buffruneio v0.2.0 h1:U4t4R6YkofJ5xHm3dJzuRpPZ0mr5MMCoAWooScCR7aA=
67 | github.com/pelletier/go-buffruneio v0.2.0/go.mod h1:JkE26KsDizTr40EUHkXVtNPvgGtbSNq5BcowyYOWdKo=
68 | github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
69 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
70 | github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
71 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
72 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
73 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
74 | github.com/russross/blackfriday v2.0.0+incompatible h1:cBXrhZNUf9C+La9/YpS+UHpUT8YD6Td9ZMSU9APFcsk=
75 | github.com/russross/blackfriday v2.0.0+incompatible/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
76 | github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
77 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
78 | github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
79 | github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
80 | github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
81 | github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
82 | github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
83 | github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
84 | github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
85 | github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
86 | github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
87 | github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
88 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
89 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
90 | github.com/spf13/viper v1.3.1 h1:5+8j8FTpnFV4nEImW/ofkzEt8VoOiLXxdYIDsB73T38=
91 | github.com/spf13/viper v1.3.1/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
92 | github.com/src-d/gcfg v1.4.0 h1:xXbNR5AlLSA315x2UO+fTSSAXCDf+Ar38/6oyGbDKQ4=
93 | github.com/src-d/gcfg v1.4.0/go.mod h1:p/UMsR43ujA89BJY9duynAwIpvqEujIH/jFlfL7jWoI=
94 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
95 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
96 | github.com/ugorji/go v1.1.2 h1:JON3E2/GPW2iDNGoSAusl1KDf5TRQ8k8q7Tp097pZGs=
97 | github.com/ugorji/go v1.1.2/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ=
98 | github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
99 | github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43 h1:BasDe+IErOQKrMVXab7UayvSlIpiyGwRvuX3EKYY7UA=
100 | github.com/ugorji/go/codec v0.0.0-20190204201341-e444a5086c43/go.mod h1:iT03XoTwV7xq/+UGwKO3UbC1nNNlopQiY61beSdrtOA=
101 | github.com/xanzy/ssh-agent v0.2.0 h1:Adglfbi5p9Z0BmK2oKU9nTG+zKfniSfnaMYB+ULd+Ro=
102 | github.com/xanzy/ssh-agent v0.2.0/go.mod h1:0NyE30eGUDliuLEHJgYte/zncp2zdTStcOnWhgSqHD8=
103 | github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
104 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
105 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
106 | golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
107 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
108 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
109 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
110 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
111 | golang.org/x/oauth2 v0.0.0-20190211225200-5f6b76b7c9dd h1:rd5tHaP+H8HLsIM51kItbLHGLDYw9hZXkSJkjdYMWmk=
112 | golang.org/x/oauth2 v0.0.0-20190211225200-5f6b76b7c9dd/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
113 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
114 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
115 | golang.org/x/sys v0.0.0-20180903190138-2b024373dcd9/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
116 | golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
117 | golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
118 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
119 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
120 | google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
121 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
122 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
123 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
124 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
125 | gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=
126 | gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
127 | gopkg.in/go-playground/validator.v8 v8.18.2 h1:lFB4DoMU6B626w8ny76MV7VX6W2VHct2GVOI3xgiMrQ=
128 | gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/RRjR0eouCJSH80/M2Y=
129 | gopkg.in/src-d/go-billy.v4 v4.2.1 h1:omN5CrMrMcQ+4I8bJ0wEhOBPanIRWzFC953IiXKdYzo=
130 | gopkg.in/src-d/go-billy.v4 v4.2.1/go.mod h1:tm33zBoOwxjYHZIE+OV8bxTWFMJLrconzFMd38aARFk=
131 | gopkg.in/src-d/go-git-fixtures.v3 v3.1.1 h1:XWW/s5W18RaJpmo1l0IYGqXKuJITWRFuA45iOf1dKJs=
132 | gopkg.in/src-d/go-git-fixtures.v3 v3.1.1/go.mod h1:dLBcvytrw/TYZsNTWCnkNF2DSIlzWYqTe3rJR56Ac7g=
133 | gopkg.in/src-d/go-git.v4 v4.9.1 h1:0oKHJZY8tM7B71378cfTg2c5jmWyNlXvestTT6WfY+4=
134 | gopkg.in/src-d/go-git.v4 v4.9.1/go.mod h1:Vtut8izDyrM8BUVQnzJ+YvmNcem2J89EmfZYCkLokZk=
135 | gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
136 | gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=
137 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
138 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
139 |
--------------------------------------------------------------------------------
/models/user.go:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import (
4 | "time"
5 |
6 | "github.com/google/go-github/github"
7 | )
8 |
9 | // User is the model used for cookies
10 | type User struct {
11 | Login string `json:"login"`
12 | Name string `json:"name"`
13 | Email string `json:"email"`
14 | }
15 |
16 | // AsAuthor returns a commit author for Github
17 | func (u *User) AsAuthor() *github.CommitAuthor {
18 | now := time.Now()
19 | return &github.CommitAuthor{Name: &u.Name, Email: &u.Email, Date: &now}
20 | }
21 |
--------------------------------------------------------------------------------
/repo/random.go:
--------------------------------------------------------------------------------
1 | package repo
2 |
3 | import (
4 | "math/rand"
5 | "time"
6 | )
7 |
8 | const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
9 | const (
10 | letterIdxBits = 6 // 6 bits to represent a letter index
11 | letterIdxMask = 1<= 0; {
21 | if remain == 0 {
22 | cache, remain = src.Int63(), letterIdxMax
23 | }
24 | if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
25 | b[i] = letterBytes[idx]
26 | i--
27 | }
28 | cache >>= letterIdxBits
29 | remain--
30 | }
31 |
32 | return string(b)
33 | }
34 |
--------------------------------------------------------------------------------
/repo/repo.go:
--------------------------------------------------------------------------------
1 | package repo
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "errors"
7 | "fmt"
8 | "log"
9 | "os"
10 | "path"
11 | "sync"
12 |
13 | "github.com/securityfirst/tent/component"
14 | "github.com/securityfirst/tent/models"
15 |
16 | git "gopkg.in/src-d/go-git.v4"
17 | "gopkg.in/src-d/go-git.v4/plumbing"
18 | "gopkg.in/src-d/go-git.v4/plumbing/object"
19 | "gopkg.in/src-d/go-git.v4/storage/memory"
20 |
21 | "github.com/google/go-github/github"
22 | "golang.org/x/oauth2"
23 | )
24 |
25 | var logger = log.New(os.Stdout, "[repo]", log.Ltime|log.Lshortfile)
26 |
27 | var (
28 | ErrNotReady = errors.New("Repository not ready")
29 | ErrFileNotFound = object.ErrFileNotFound
30 | )
31 |
32 | const (
33 | actionCreate = iota
34 | actionUpdate
35 | actionDelete
36 | )
37 |
38 | var commitMsg = map[int]string{
39 | actionCreate: "Create",
40 | actionUpdate: "Update",
41 | actionDelete: "Delete",
42 | }
43 |
44 | func Local(dir, branch string) (*Repo, error) {
45 | logger.Printf("Using %q", dir)
46 | r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: fmt.Sprintf("file://%s", dir)})
47 | if err != nil {
48 | return nil, err
49 | }
50 | if branch == "" {
51 | branch = "master"
52 | }
53 | return &Repo{repo: r, name: path.Base(dir), branch: branch}, nil
54 | }
55 |
56 | func New(owner, name, branch string) (*Repo, error) {
57 | address := repoAddress(owner, name)
58 | logger.Printf("Using %q", address)
59 | r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: address})
60 | if err != nil {
61 | return nil, err
62 | }
63 | if branch == "" {
64 | branch = "master"
65 | }
66 | return &Repo{repo: r, name: name, owner: owner, branch: branch}, nil
67 | }
68 |
69 | type Repo struct {
70 | sync.RWMutex
71 | owner string
72 | name string
73 | branch string
74 | conf *oauth2.Config
75 | repo *git.Repository
76 | commit *object.Commit
77 | categories map[string][]*component.Category
78 | assets []*component.Asset
79 | forms []*component.Form
80 | }
81 |
82 | func (r *Repo) SetConf(c *oauth2.Config) { r.conf = c }
83 |
84 | func (r *Repo) Tree(locale string, html bool) interface{} {
85 | r.RLock()
86 | defer r.RUnlock()
87 |
88 | var cats = make([]interface{}, 0, len(r.categories))
89 | for _, i := range r.Categories(locale) {
90 | cats = append(cats, r.Category(i, locale).Tree(html))
91 | }
92 |
93 | var ass = make([]string, len(r.assets))
94 | for i := range r.assets {
95 | ass[i] = r.assets[i].ID
96 | }
97 |
98 | var forms = make([]*component.Form, 0)
99 | for i := range r.forms {
100 | if r.forms[i].Locale != locale {
101 | continue
102 | }
103 | forms = append(forms, r.forms[i])
104 | }
105 |
106 | return map[string]interface{}{
107 | "categories": cats,
108 | "assets": ass,
109 | "forms": forms,
110 | }
111 | }
112 |
113 | func (r *Repo) client(token string) *github.Client {
114 | return github.NewClient(r.conf.Client(oauth2.NoContext, &oauth2.Token{AccessToken: token}))
115 | }
116 |
117 | func (r *Repo) Handler() RepoHandler { return RepoHandler{r} }
118 |
119 | func (r *Repo) Locale() []string {
120 | var locale = make([]string, 0, len(r.categories))
121 | for k := range r.categories {
122 | locale = append(locale, k)
123 | }
124 | return locale
125 | }
126 |
127 | func (r *Repo) All(locale string) []component.Component {
128 | var list []component.Component
129 | for _, cat := range r.categories[locale] {
130 | list = append(list, cat)
131 | for _, id := range cat.Subcategories() {
132 | sub := cat.Sub(id)
133 | list = append(list, sub)
134 | for _, diff := range sub.Difficulties() {
135 | for _, id := range diff.ItemNames() {
136 | list = append(list, diff.Item(id))
137 | }
138 | if check := diff.Checks(); check.HasChildren() {
139 | list = append(list, check)
140 | }
141 | }
142 | }
143 | }
144 | for _, form := range r.forms {
145 | if form.Locale != locale {
146 | continue
147 | }
148 | list = append(list, form)
149 | }
150 | return list
151 | }
152 |
153 | func (r *Repo) hash() string {
154 | if r.commit != nil {
155 | return r.commit.Hash.String()
156 | }
157 | return "n/a"
158 | }
159 |
160 | func (r *Repo) MarshalJSON() ([]byte, error) {
161 | return json.Marshal(map[string]interface{}{
162 | "owner": r.owner,
163 | "name": r.name,
164 | "commit": r.hash(),
165 | })
166 | }
167 |
168 | func (r *Repo) String() string {
169 | return fmt.Sprintf("%s/%s %s", r.owner, r.name, r.hash())
170 | }
171 |
172 | func (r *Repo) Pull() {
173 | r.Lock()
174 | defer r.Unlock()
175 |
176 | err := r.repo.Fetch(&git.FetchOptions{})
177 | if err != nil && err != git.NoErrAlreadyUpToDate {
178 | logger.Println("Pull failed:", err)
179 | return
180 | }
181 | branch := plumbing.ReferenceName("refs/remotes/origin/" + r.branch)
182 | hash, err := r.repo.Reference(branch, false)
183 | if err != nil {
184 | logger.Printf("Reference %q failed:", branch, err)
185 | return
186 | }
187 | if r.commit != nil && r.commit.Hash == hash.Hash() {
188 | return
189 | }
190 | if r.commit != nil {
191 | logger.Println("Changing commit from", r.commit.Hash, "to", hash)
192 | } else {
193 | logger.Println("Checkout with", hash)
194 | }
195 | r.commit, err = r.repo.CommitObject(hash.Hash())
196 | if err != nil {
197 | logger.Println("Commit failed:", err)
198 | return
199 | }
200 | var parser component.Parser
201 | tree, err := r.commit.Tree()
202 | if err != nil {
203 | logger.Println("Tree failed:", err)
204 | return
205 | }
206 | if err := parser.Parse(tree); err != nil {
207 | logger.Println("Parsing failed:", err)
208 | return
209 | }
210 | r.categories = parser.Categories()
211 | r.assets = parser.Assets()
212 | r.forms = parser.Forms()
213 | }
214 |
215 | func (r *Repo) file(c component.Component) (*object.File, error) {
216 | if r.commit == nil {
217 | return nil, ErrNotReady
218 | }
219 | r.RLock()
220 | defer r.RUnlock()
221 | return r.commit.File(c.Path()[:])
222 | }
223 |
224 | func (r *Repo) Get(c component.Component) (string, error) {
225 | f, err := r.file(c)
226 | if err != nil {
227 | return "", err
228 | }
229 | return f.Contents()
230 | }
231 |
232 | func (r *Repo) Asset(id string) *component.Asset {
233 | r.RLock()
234 | defer r.RUnlock()
235 |
236 | for _, a := range r.assets {
237 | if a.ID == id {
238 | return a
239 | }
240 | }
241 | return nil
242 | }
243 |
244 | func (r *Repo) Forms(locale string) []string {
245 | r.RLock()
246 | defer r.RUnlock()
247 | var s []string
248 | for _, v := range r.forms {
249 | if v.Locale == locale {
250 | s = append(s, v.ID)
251 | }
252 | }
253 | return s
254 | }
255 |
256 | func (r *Repo) Form(id string, locale string) *component.Form {
257 | r.RLock()
258 | defer r.RUnlock()
259 |
260 | for _, f := range r.forms {
261 | if f.ID == id && f.Locale == locale {
262 | return f
263 | }
264 | }
265 | return nil
266 | }
267 |
268 | func (r *Repo) Category(cat, locale string) *component.Category {
269 | r.RLock()
270 | defer r.RUnlock()
271 |
272 | for _, c := range r.categories[locale] {
273 | if c.ID == cat {
274 | return c
275 | }
276 | }
277 | return nil
278 | }
279 |
280 | func (r *Repo) Categories(locale string) []string {
281 | r.RLock()
282 | defer r.RUnlock()
283 | var s []string
284 | for _, v := range r.categories[locale] {
285 | s = append(s, v.ID)
286 | }
287 | return s
288 | }
289 |
290 | func (r *Repo) ComponentHash(c component.Component) (string, error) {
291 | f, err := r.file(c)
292 | if err != nil {
293 | return "", err
294 | }
295 | return f.Hash.String(), nil
296 | }
297 |
298 | func (r *Repo) Create(c component.Component, u models.User, token string) error {
299 | return r.request(c, actionCreate, u, token)
300 | }
301 |
302 | func (r *Repo) Delete(c component.Component, u models.User, token string) error {
303 | return r.request(c, actionDelete, u, token)
304 | }
305 |
306 | func (r *Repo) Update(c component.Component, u models.User, token string) error {
307 | return r.request(c, actionUpdate, u, token)
308 | }
309 |
310 | func (r *Repo) request(c component.Component, action int, u models.User, token string) (err error) {
311 | file := c.Path()
312 | msg := fmt.Sprintf("%s %s", commitMsg[action], file)
313 | commit := &github.RepositoryContentFileOptions{
314 | Message: &msg, Author: u.AsAuthor(),
315 | }
316 | switch action {
317 | case actionCreate:
318 | commit.Content = []byte(c.Contents())
319 | _, _, err = r.client(token).Repositories.CreateFile(context.Background(), r.owner, r.name, file, commit)
320 | case actionUpdate:
321 | commit.SHA = strPtr(c.SHA())
322 | commit.Content = []byte(c.Contents())
323 | _, _, err = r.client(token).Repositories.UpdateFile(context.Background(), r.owner, r.name, file, commit)
324 | case actionDelete:
325 | commit.SHA = strPtr(c.SHA())
326 | _, _, err = r.client(token).Repositories.DeleteFile(context.Background(), r.owner, r.name, file, commit)
327 | }
328 | if err == nil {
329 | go r.Pull()
330 | }
331 | return err
332 | }
333 |
334 | func strPtr(s string) *string { return &s }
335 |
336 | func repoAddress(owner, name string) string {
337 | return fmt.Sprintf("https://github.com/%s/%s", owner, name)
338 | }
339 |
340 | func uploadAddress(owner, name, file string) string {
341 | return fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s", owner, name, file)
342 | }
343 |
--------------------------------------------------------------------------------
/repo/repo_handlers.go:
--------------------------------------------------------------------------------
1 | package repo
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "errors"
7 | "io"
8 | "log"
9 | "net/http"
10 | "path"
11 | "path/filepath"
12 | "sort"
13 |
14 | "github.com/gin-gonic/gin"
15 | "github.com/google/go-github/github"
16 |
17 | "github.com/securityfirst/tent/component"
18 | "github.com/securityfirst/tent/models"
19 | "gopkg.in/src-d/go-git.v4/plumbing/object"
20 | )
21 |
22 | var (
23 | ErrExists = errors.New("existing id")
24 | ErrNotFound = errors.New("not found")
25 | ErrHasChildren = errors.New("element has children")
26 | ErrLanguage = errors.New("invalid language")
27 | )
28 |
29 | type RepoHandler struct {
30 | repo *Repo
31 | }
32 |
33 | func (r *RepoHandler) err(c *gin.Context, status int, err error) {
34 | if re, ok := err.(*github.ErrorResponse); ok {
35 | status = re.Response.StatusCode
36 | err = errors.New(re.Message)
37 | }
38 | c.JSON(status, gin.H{"error": err.Error()})
39 | c.Abort()
40 | }
41 |
42 | func (r *RepoHandler) cmp(c *gin.Context) component.Component {
43 | asset, ok := c.Get("asset")
44 | if ok {
45 | return asset.(*component.Asset)
46 | }
47 | form, ok := c.Get("form")
48 | if ok {
49 | return form.(*component.Form)
50 | }
51 | cat, ok := c.Get("cat")
52 | if !ok {
53 | return nil
54 | }
55 | sub, ok := c.Get("sub")
56 | if !ok {
57 | return cat.(component.Component)
58 | }
59 | diff, ok := c.Get("diff")
60 | if !ok {
61 | return sub.(component.Component)
62 | }
63 | if item, ok := c.Get("item"); ok {
64 | return item.(component.Component)
65 | }
66 | if check, ok := c.Get("checks"); ok {
67 | return check.(component.Component)
68 | }
69 | return diff.(component.Component)
70 | }
71 |
72 | func (r *RepoHandler) token(c *gin.Context) string {
73 | return c.MustGet("token").(string)
74 | }
75 |
76 | func (r *RepoHandler) user(c *gin.Context) models.User {
77 | return c.MustGet("user").(models.User)
78 | }
79 |
80 | func (r *RepoHandler) asset(c *gin.Context) *component.Asset {
81 | return c.MustGet("asset").(*component.Asset)
82 | }
83 |
84 | func (r *RepoHandler) form(c *gin.Context) *component.Form {
85 | return c.MustGet("form").(*component.Form)
86 | }
87 |
88 | func (r *RepoHandler) cat(c *gin.Context) *component.Category {
89 | return c.MustGet("cat").(*component.Category)
90 | }
91 |
92 | func (r *RepoHandler) sub(c *gin.Context) *component.Subcategory {
93 | return c.MustGet("sub").(*component.Subcategory)
94 | }
95 |
96 | func (r *RepoHandler) diff(c *gin.Context) *component.Difficulty {
97 | return c.MustGet("diff").(*component.Difficulty)
98 | }
99 |
100 | func (r *RepoHandler) item(c *gin.Context) *component.Item {
101 | return c.MustGet("item").(*component.Item)
102 | }
103 |
104 | func (r *RepoHandler) checks(c *gin.Context) *component.Checklist {
105 | return c.MustGet("checks").(*component.Checklist)
106 | }
107 |
108 | func (r *RepoHandler) locale(c *gin.Context) string {
109 | return c.MustGet("locale").(string)
110 | }
111 |
112 | func (r *RepoHandler) ParseLocale(c *gin.Context) {
113 | s := c.Request.Header.Get("X-Tent-Language")
114 | if s == "" {
115 | s = "en"
116 | }
117 | if len(s) != 2 {
118 | r.err(c, http.StatusBadRequest, ErrLanguage)
119 | return
120 | }
121 | c.Set("locale", s)
122 | }
123 |
124 | func (r *RepoHandler) IsNew(c *gin.Context) {
125 | var cmp component.Component
126 | switch t := r.cmp(c).(type) {
127 | case *component.Category:
128 | if cat := r.repo.Category(t.ID, r.locale(c)); cat != nil {
129 | cmp = cat
130 | }
131 | case *component.Subcategory:
132 | if sub := r.cat(c).Sub(t.ID); sub != nil {
133 | cmp = sub
134 | }
135 | case *component.Difficulty:
136 | if item := r.sub(c).Difficulty(t.ID); item != nil {
137 | cmp = item
138 | }
139 | case *component.Item:
140 | if item := r.diff(c).Item(t.ID); item != nil {
141 | cmp = item
142 | }
143 | }
144 | if cmp != nil {
145 | r.err(c, http.StatusConflict, ErrExists)
146 | }
147 | }
148 |
149 | func (r *RepoHandler) CanDelete(c *gin.Context) {
150 | var cmp component.Component
151 | switch t := r.cmp(c).(type) {
152 | case *component.Category:
153 | if cat := r.repo.Category(t.ID, r.locale(c)); cat != nil {
154 | cmp = cat
155 | }
156 | case *component.Subcategory:
157 | if sub := r.cat(c).Sub(t.ID); sub != nil {
158 | cmp = sub
159 | }
160 | case *component.Difficulty:
161 | if diff := r.sub(c).Difficulty(t.ID); diff != nil {
162 | cmp = diff
163 | }
164 | case *component.Item:
165 | if item := r.diff(c).Item(t.ID); item != nil {
166 | cmp = item
167 | }
168 | }
169 | if cmp == nil {
170 | r.err(c, http.StatusNotFound, ErrNotFound)
171 | return
172 | }
173 | if cmp.HasChildren() {
174 | r.err(c, http.StatusForbidden, ErrHasChildren)
175 | return
176 | }
177 | }
178 |
179 | // SetCat loads the category using the url parameter
180 | func (r *RepoHandler) SetCat(c *gin.Context) {
181 | cat := r.repo.Category(c.Param("cat"), r.locale(c))
182 | if cat == nil {
183 | r.err(c, http.StatusNotFound, ErrNotFound)
184 | return
185 | }
186 | c.Set("cat", cat)
187 | }
188 |
189 | func (r *RepoHandler) ParseCat(c *gin.Context) {
190 | var cat component.Category
191 | if err := c.BindJSON(&cat); err != nil {
192 | r.err(c, http.StatusBadRequest, err)
193 | return
194 | }
195 | cat.ID, cat.Locale = c.Param("cat"), r.locale(c)
196 | c.Set("cat", &cat)
197 | }
198 |
199 | func (r *RepoHandler) SetSub(c *gin.Context) {
200 | r.SetCat(c)
201 | sub := r.cat(c).Sub(c.Param("sub"))
202 | if sub == nil {
203 | r.err(c, http.StatusNotFound, ErrNotFound)
204 | return
205 | }
206 | c.Set("sub", sub)
207 | }
208 |
209 | func (r *RepoHandler) ParseSub(c *gin.Context) {
210 | r.SetCat(c)
211 | var sub component.Subcategory
212 | if err := c.BindJSON(&sub); err != nil {
213 | r.err(c, http.StatusBadRequest, err)
214 | return
215 | }
216 | sub.SetParent(r.cat(c))
217 | sub.ID = c.Param("sub")
218 | log.Println(sub)
219 | c.Set("sub", &sub)
220 | }
221 |
222 | func (r *RepoHandler) SetDiff(c *gin.Context) {
223 | r.SetSub(c)
224 | diff := r.sub(c).Difficulty(c.Param("diff"))
225 | if diff == nil {
226 | r.err(c, http.StatusNotFound, ErrNotFound)
227 | return
228 | }
229 | c.Set("diff", diff)
230 | }
231 |
232 | func (r *RepoHandler) ParseDiff(c *gin.Context) {
233 | r.SetSub(c)
234 | var diff component.Difficulty
235 | if err := c.BindJSON(&diff); err != nil {
236 | r.err(c, http.StatusBadRequest, err)
237 | return
238 | }
239 | diff.SetParent(r.sub(c))
240 | diff.ID = c.Param("diff")
241 | c.Set("diff", &diff)
242 | }
243 |
244 | func (r *RepoHandler) SetItem(c *gin.Context) {
245 | r.SetDiff(c)
246 | item := r.diff(c).Item(c.Param("item"))
247 | if item == nil {
248 | r.err(c, http.StatusNotFound, ErrNotFound)
249 | return
250 | }
251 | c.Set("item", item)
252 | }
253 |
254 | func (r *RepoHandler) ParseItem(c *gin.Context) {
255 | r.SetDiff(c)
256 | var item component.Item
257 | if err := c.BindJSON(&item); err != nil {
258 | r.err(c, http.StatusBadRequest, err)
259 | return
260 | }
261 | item.SetParent(r.diff(c))
262 | item.ID = c.Param("item")
263 | c.Set("item", &item)
264 | }
265 |
266 | func (r *RepoHandler) SetCheck(c *gin.Context) {
267 | r.SetDiff(c)
268 | diff := r.diff(c)
269 | if diff.Checks() == nil {
270 | diff.SetChecks(&component.Checklist{Checks: []component.Check{}})
271 | }
272 | c.Set("checks", diff.Checks())
273 | }
274 |
275 | func (r *RepoHandler) ParseCheck(c *gin.Context) {
276 | r.SetDiff(c)
277 | var check component.Checklist
278 | if err := c.BindJSON(&check); err != nil {
279 | r.err(c, http.StatusBadRequest, err)
280 | return
281 | }
282 | check.SetParent(r.diff(c))
283 | c.Set("checks", &check)
284 | }
285 |
286 | func (r *RepoHandler) SetAsset(c *gin.Context) {
287 | c.Set("asset", r.repo.Asset(c.Param("asset")))
288 | }
289 |
290 | func (r *RepoHandler) ParseAsset(c *gin.Context) {
291 | file := c.Request.Header.Get("file")
292 | if file == "" {
293 | file = "upload.jpg"
294 | }
295 | b := bytes.NewBuffer(nil)
296 | io.Copy(b, c.Request.Body)
297 | c.Set("asset", &component.Asset{
298 | ID: RandStringBytesMaskImprSrc(10) + filepath.Ext(file),
299 | Content: b.String(),
300 | })
301 | }
302 |
303 | // SetForm loads the form using the url parameter
304 | func (r *RepoHandler) SetForm(c *gin.Context) {
305 | form := r.repo.Form(c.Param("form"), r.locale(c))
306 | if form == nil {
307 | r.err(c, http.StatusNotFound, ErrNotFound)
308 | return
309 | }
310 | c.Set("form", form)
311 | }
312 |
313 | func (r *RepoHandler) ParseForm(c *gin.Context) {
314 | var form component.Form
315 | if err := c.BindJSON(&form); err != nil {
316 | r.err(c, http.StatusBadRequest, err)
317 | return
318 | }
319 | form.ID, form.Locale = c.Param("form"), r.locale(c)
320 | c.Set("form", &form)
321 | }
322 |
323 | func (r *RepoHandler) Info(c *gin.Context) {
324 | c.JSON(http.StatusOK, gin.H{
325 | "user": r.user(c),
326 | "repo": r.repo,
327 | })
328 | }
329 |
330 | func (r *RepoHandler) Root(c *gin.Context) {
331 | cats := r.repo.Categories(r.locale(c))
332 | sort.Strings(cats)
333 | c.JSON(http.StatusOK, gin.H{
334 | "categories": cats,
335 | })
336 | }
337 |
338 | func (r *RepoHandler) ShowChecks(c *gin.Context) {
339 | cmp := r.cmp(c)
340 | hash, err := r.repo.ComponentHash(cmp)
341 | if err != nil && err != object.ErrFileNotFound {
342 | r.err(c, http.StatusInternalServerError, err)
343 | return
344 | }
345 | cmp.(*component.Checklist).Hash = hash
346 | c.JSON(http.StatusOK, cmp)
347 | }
348 |
349 | func (r *RepoHandler) UpdateChecks(c *gin.Context) {
350 | hash, err := r.repo.ComponentHash(r.cmp(c))
351 | if err != nil && err != object.ErrFileNotFound {
352 | r.err(c, http.StatusInternalServerError, err)
353 | return
354 | }
355 | if hash != "" {
356 | r.Update(c)
357 | } else {
358 | r.Create(c)
359 | }
360 | }
361 |
362 | func (r *RepoHandler) Show(c *gin.Context) {
363 | cmp := r.cmp(c)
364 | hash, err := r.repo.ComponentHash(cmp)
365 | if err != nil {
366 | if _, ok := cmp.(*component.Checklist); !ok || err != object.ErrFileNotFound {
367 | r.err(c, http.StatusInternalServerError, err)
368 | return
369 | }
370 | }
371 | var out interface{}
372 | switch t := cmp.(type) {
373 | case *component.Category:
374 | v := *t
375 | v.Hash = hash
376 | out = &v
377 | case *component.Subcategory:
378 | v := *t
379 | v.Hash = hash
380 | out = &v
381 | case *component.Difficulty:
382 | v := *t
383 | v.Hash = hash
384 | out = &v
385 | case *component.Item:
386 | v := *t
387 | v.Hash = hash
388 | out = &v
389 | case *component.Checklist:
390 | v := *t
391 | v.Hash = hash
392 | out = &v
393 | case *component.Form:
394 | v := *t
395 | v.Hash = hash
396 | out = &v
397 | }
398 | c.JSON(http.StatusOK, out)
399 | }
400 |
401 | func (r *RepoHandler) Create(c *gin.Context) {
402 | if err := r.repo.Create(r.cmp(c), r.user(c), r.token(c)); err != nil {
403 | r.err(c, http.StatusInternalServerError, err)
404 | return
405 | }
406 | c.Writer.WriteHeader(http.StatusCreated)
407 | }
408 |
409 | func (r *RepoHandler) Update(c *gin.Context) {
410 | if err := r.repo.Update(r.cmp(c), r.user(c), r.token(c)); err != nil {
411 | r.err(c, http.StatusInternalServerError, err)
412 | return
413 | }
414 | c.Writer.WriteHeader(http.StatusNoContent)
415 | }
416 |
417 | func (r *RepoHandler) Delete(c *gin.Context) {
418 | if err := r.repo.Delete(r.cmp(c), r.user(c), r.token(c)); err != nil {
419 | r.err(c, http.StatusInternalServerError, err)
420 | return
421 | }
422 | c.Writer.WriteHeader(http.StatusNoContent)
423 | }
424 |
425 | func (r *RepoHandler) AssetShow(c *gin.Context) {
426 | a := r.asset(c)
427 | var ct string
428 | switch path.Ext(a.ID) {
429 | case ".png":
430 | ct = "image/png"
431 | case ".jpg", "jpeg":
432 | ct = "image/jpeg"
433 | default:
434 | ct = "application/octet-stream"
435 | }
436 | c.Writer.Header().Set("content-type", ct)
437 | c.Writer.WriteString(r.asset(c).Contents())
438 | }
439 |
440 | func (r *RepoHandler) AssetCreate(c *gin.Context) {
441 | asset := r.asset(c)
442 | if err := r.repo.Create(asset, r.user(c), r.token(c)); err != nil {
443 | r.err(c, http.StatusInternalServerError, err)
444 | return
445 | }
446 | c.JSON(201, gin.H{"id": asset.ID})
447 | }
448 |
449 | func (r *RepoHandler) Tree(c *gin.Context) {
450 | writeJSON(c, http.StatusOK, r.repo.Tree(r.locale(c), c.Query("content") == "html"))
451 | }
452 |
453 | func writeJSON(c *gin.Context, status int, obj interface{}) {
454 | header := c.Writer.Header()
455 | if val := header["Content-Type"]; len(val) == 0 {
456 | header["Content-Type"] = []string{"application/json; charset=utf-8"}
457 | }
458 | c.Status(status)
459 | e := json.NewEncoder(c.Writer)
460 | e.SetEscapeHTML(false)
461 | e.Encode(obj)
462 | }
463 |
--------------------------------------------------------------------------------
/tent.go:
--------------------------------------------------------------------------------
1 | package tent
2 |
3 | import (
4 | "time"
5 |
6 | "log"
7 |
8 | "github.com/gin-gonic/gin"
9 | "github.com/securityfirst/tent/auth"
10 | "github.com/securityfirst/tent/repo"
11 | )
12 |
13 | const (
14 | pathInfo = "/"
15 | pathTree = "/api/tree"
16 | pathRepo = "/api/repo"
17 | pathUpdate = "/api/repo/update"
18 | pathCategory = "/api/repo/category/:cat"
19 | pathSubcategory = "/api/repo/category/:cat/:sub"
20 | pathDifficulty = "/api/repo/category/:cat/:sub/:diff"
21 | pathItem = "/api/repo/category/:cat/:sub/:diff/item/:item"
22 | pathCheck = "/api/repo/category/:cat/:sub/:diff/checks"
23 | pathAsset = "/api/repo/asset"
24 | pathAssetID = "/api/repo/asset/:asset"
25 | pathForm = "/api/repo/form/:form"
26 | )
27 |
28 | func New(r *repo.Repo) *Tent {
29 | return &Tent{repo: r}
30 | }
31 |
32 | type Tent struct {
33 | repo *repo.Repo
34 | }
35 |
36 | func (o *Tent) Register(root *gin.RouterGroup, c auth.Config) {
37 | var (
38 | engine = auth.NewEngine(c, root)
39 | hookCh = make(chan struct{})
40 | h = o.repo.Handler()
41 | )
42 | o.repo.SetConf(c.OAuth(root))
43 |
44 | // Free handlers
45 | root.POST(pathUpdate, func(*gin.Context) { // Hook for github
46 | select {
47 | case hookCh <- struct{}{}: // starts an update
48 | default: // discard
49 | }
50 | })
51 | locale := root.Use(h.ParseLocale)
52 | locale.GET(pathTree, h.Tree)
53 | locale.GET(pathInfo, h.Info)
54 | locale.GET(pathRepo, h.Root)
55 | locale.GET(pathCategory, h.SetCat, h.Show)
56 | locale.GET(pathSubcategory, h.SetSub, h.Show)
57 | locale.GET(pathDifficulty, h.SetDiff, h.Show)
58 | locale.GET(pathItem, h.SetItem, h.Show)
59 | locale.GET(pathCheck, h.SetCheck, h.ShowChecks)
60 | locale.GET(pathAssetID, h.SetAsset, h.AssetShow)
61 | locale.GET(pathForm, h.SetForm, h.Show)
62 |
63 | // Locale and Authorized handlers
64 | authorized := root.Use(engine.EnsureUser, h.ParseLocale)
65 |
66 | authorized.PUT(pathCategory, h.ParseCat, h.Update)
67 | authorized.DELETE(pathCategory, h.ParseCat, h.CanDelete, h.Delete)
68 | authorized.POST(pathCategory, h.ParseCat, h.IsNew, h.Create)
69 |
70 | authorized.PUT(pathSubcategory, h.ParseSub, h.Update)
71 | authorized.DELETE(pathSubcategory, h.ParseSub, h.CanDelete, h.Delete)
72 | authorized.POST(pathSubcategory, h.ParseSub, h.IsNew, h.Create)
73 |
74 | authorized.PUT(pathDifficulty, h.ParseDiff, h.Update)
75 | authorized.DELETE(pathDifficulty, h.ParseDiff, h.CanDelete, h.Delete)
76 | authorized.POST(pathDifficulty, h.ParseDiff, h.IsNew, h.Create)
77 |
78 | authorized.PUT(pathItem, h.ParseItem, h.Update)
79 | authorized.DELETE(pathItem, h.ParseItem, h.CanDelete, h.Delete)
80 | authorized.POST(pathItem, h.ParseItem, h.IsNew, h.Create)
81 |
82 | authorized.PUT(pathCheck, h.ParseCheck, h.UpdateChecks)
83 |
84 | authorized.POST(pathAsset, h.ParseAsset, h.AssetCreate)
85 |
86 | authorized.PUT(pathForm, h.ParseForm, h.Update)
87 | authorized.DELETE(pathForm, h.ParseForm, h.CanDelete, h.Delete)
88 | authorized.POST(pathForm, h.ParseForm, h.IsNew, h.Create)
89 |
90 | loop(o.repo.Pull, 10*time.Minute, hookCh)
91 |
92 | // Force first update
93 | log.Println("First repo update...")
94 | hookCh <- struct{}{}
95 |
96 | }
97 |
98 | func loop(action func(), every time.Duration, trigger <-chan struct{}) <-chan struct{} {
99 | t := time.NewTicker(every)
100 | stop := make(chan struct{})
101 | go func() {
102 | for {
103 | select {
104 | case <-t.C:
105 | action()
106 | case <-trigger:
107 | action()
108 | case <-stop:
109 | t.Stop()
110 | return
111 | }
112 | }
113 | }()
114 | return stop
115 | }
116 |
--------------------------------------------------------------------------------
/tent/cmd/root.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 NAME HERE
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package cmd
16 |
17 | import (
18 | "fmt"
19 | "log"
20 | "os"
21 |
22 | "github.com/securityfirst/tent/auth"
23 | "github.com/securityfirst/tent/repo"
24 | "github.com/securityfirst/tent/transifex"
25 | "github.com/spf13/cobra"
26 | "github.com/spf13/viper"
27 | )
28 |
29 | var cfgFile string
30 |
31 | var config struct {
32 | Server struct {
33 | Port int
34 | Prefix string
35 | }
36 | Github struct {
37 | Handler, Project, Branch string
38 | }
39 | Transifex struct {
40 | Project transifex.Project
41 | Language string
42 | Username string
43 | Password string
44 | RequestPerHour int
45 | Filter string
46 | }
47 | PauseOnError bool
48 | Root string
49 | auth.Config
50 | }
51 |
52 | func newRepo() (*repo.Repo, error) {
53 | return repo.New(config.Github.Handler, config.Github.Project, config.Github.Branch)
54 | }
55 |
56 | var RootCmd = &cobra.Command{
57 | Use: "tent",
58 | Short: "Repo based CMS",
59 | Long: `Tent is a Content Managment System that store data in a Github Repository.`,
60 | }
61 |
62 | // Execute adds all child commands to the root command sets flags appropriately.
63 | func Execute() {
64 | if err := RootCmd.Execute(); err != nil {
65 | fmt.Println(err)
66 | os.Exit(-1)
67 | }
68 | }
69 |
70 | func init() {
71 | cobra.OnInitialize(initConfig)
72 | RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.tent.yaml)")
73 | log.SetFlags(log.Ltime | log.Lshortfile)
74 | }
75 |
76 | // initConfig reads in config file and ENV variables if set.
77 | func initConfig() {
78 | if cfgFile != "" { // enable ability to specify config file via flag
79 | viper.SetConfigFile(cfgFile)
80 | }
81 |
82 | viper.SetConfigName(".tent") // name of config file (without extension)
83 | viper.AddConfigPath(".") // adding current directory as first search path
84 | viper.AddConfigPath("$HOME") // adding home directory as second
85 | viper.AutomaticEnv() // read in environment variables that match
86 |
87 | // If a config file is found, read it in.
88 | if err := viper.ReadInConfig(); err != nil {
89 | return
90 | }
91 | log.Println("Using config file:", viper.ConfigFileUsed())
92 | if err := viper.Unmarshal(&config); err != nil {
93 | log.Fatal("Error:", err)
94 | }
95 | if config.Transifex.Language == "" {
96 | config.Transifex.Language = "en"
97 | }
98 | if config.Transifex.RequestPerHour == 0 {
99 | config.Transifex.RequestPerHour = 6000
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/tent/cmd/run.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 NAME HERE
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package cmd
16 |
17 | import (
18 | "context"
19 | "flag"
20 | "fmt"
21 | "log"
22 | "net/http"
23 | "os"
24 | "os/signal"
25 | "time"
26 |
27 | "github.com/gin-gonic/gin"
28 | "github.com/securityfirst/tent"
29 | "github.com/spf13/cobra"
30 | )
31 |
32 | // runCmd respresents the run command
33 | var runCmd = &cobra.Command{
34 | Use: "run",
35 | Short: "Starts CMS",
36 | Long: `Starts the Tent CMS`,
37 | Run: func(cmd *cobra.Command, args []string) {
38 | if config.ID == "" || config.Secret == "" {
39 | flag.Usage()
40 | os.Exit(1)
41 | }
42 | e := gin.Default()
43 | srv := &http.Server{
44 | Addr: fmt.Sprintf(":%v", config.Server.Port),
45 | Handler: e,
46 | }
47 | r, err := newRepo()
48 | if err != nil {
49 | log.Fatalf("Repo error: %s", err)
50 | }
51 |
52 | o := tent.New(r)
53 | o.Register(e.Group(config.Server.Prefix), config.Config)
54 |
55 | stop := make(chan os.Signal, 1)
56 | signal.Notify(stop, os.Interrupt)
57 | go srv.ListenAndServe()
58 |
59 | <-stop
60 | log.Println("Shutting down the server...")
61 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
62 | defer cancel()
63 | srv.Shutdown(ctx)
64 | },
65 | }
66 |
67 | func init() {
68 | RootCmd.AddCommand(runCmd)
69 | }
70 |
--------------------------------------------------------------------------------
/tent/cmd/transifex.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 NAME HERE
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package cmd
16 |
17 | import "github.com/spf13/cobra"
18 |
19 | // transifexCmd respresents the transifex command
20 | var transifexCmd = &cobra.Command{
21 | Use: "transifex",
22 | Short: "Transifex commands",
23 | Long: `Commands for handling Transifex translations`,
24 | }
25 |
26 | func init() {
27 | RootCmd.AddCommand(transifexCmd)
28 | }
29 |
--------------------------------------------------------------------------------
/tent/cmd/transifex_download.go:
--------------------------------------------------------------------------------
1 | package cmd
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "log"
8 | "os"
9 | "os/signal"
10 | "path/filepath"
11 | "strings"
12 | "time"
13 |
14 | "github.com/securityfirst/tent/utils"
15 |
16 | "github.com/securityfirst/tent/component"
17 |
18 | "github.com/securityfirst/tent/transifex"
19 | "github.com/spf13/cobra"
20 | )
21 |
22 | var mute = true
23 |
24 | // downloadCmd respresents the download command
25 | var downloadCmd = &cobra.Command{
26 | Use: "download",
27 | Short: "Uploads latest contents to Transifex",
28 | Long: `Downloads the lastest version of Transifex contents and uploads them to Tent.`,
29 | Run: downloadRun,
30 | }
31 |
32 | func init() {
33 | transifexCmd.AddCommand(downloadCmd)
34 | }
35 |
36 | var (
37 | client transifex.Client
38 | parser = component.NewResourceParser()
39 | )
40 |
41 | func downloadRun(cmd *cobra.Command, args []string) {
42 | client = transifex.NewClient(config.Transifex.Project, config.Transifex.Username, config.Transifex.Password)
43 | client.RateLimit(time.Hour, config.Transifex.RequestPerHour)
44 | difficulties, err := downloadDifficulties(args)
45 | if err != nil {
46 | log.Fatalf("difficulties: %s", err)
47 | }
48 |
49 | r, err := newRepo()
50 | r.Pull()
51 |
52 | quit := make(chan os.Signal)
53 | signal.Notify(quit, os.Interrupt)
54 |
55 | go func() {
56 | defer func() { quit <- nil }()
57 | for _, cmp := range r.All(config.Transifex.Language) {
58 | if err := parseComponent(cmp, args); err != nil {
59 | log.Println(cmp.Path(), err)
60 | }
61 | }
62 | }()
63 | <-quit
64 | saveResults(parser, difficulties)
65 |
66 | }
67 |
68 | func parseComponent(cmp component.Component, langs []string) error {
69 | defer func() {
70 | if recover() != nil {
71 | log.Println(cmp)
72 | }
73 | }()
74 | resource := cmp.Resource()
75 | translations, err := downloadTranslation(filepath.Join(config.Root, resource.Slug+".json"), resource)
76 | if err != nil {
77 | return err
78 | }
79 | for _, t := range langs {
80 | target, ok := translations[t]
81 | if !ok || target == translations["en"] {
82 | continue
83 | }
84 | if err := json.NewDecoder(strings.NewReader(target)).Decode(&resource.Content); err != nil {
85 | return fmt.Errorf("%s: %s", t, err)
86 | }
87 | if err := parser.Parse(cmp, &resource, t[:2]); err != nil {
88 | return fmt.Errorf("%s: %s", t, err)
89 | }
90 | }
91 | return nil
92 | }
93 |
94 | func downloadTranslation(cachePath string, resource component.Resource) (map[string]string, error) {
95 | var translations = (map[string]string)(nil)
96 | if _, err := os.Stat(cachePath); err != nil {
97 | translations, err = client.DownloadTranslations(resource.Slug)
98 | if err != nil {
99 | return nil, err
100 | }
101 | f, err := os.OpenFile(cachePath, os.O_WRONLY|os.O_CREATE, 0644)
102 | if err != nil {
103 | return nil, err
104 | }
105 | defer f.Close()
106 | if err := json.NewEncoder(f).Encode(translations); err != nil {
107 | return nil, err
108 | }
109 | }
110 | f, err := os.Open(cachePath)
111 | if err != nil {
112 | return nil, err
113 | }
114 | defer f.Close()
115 | if err := json.NewDecoder(f).Decode(&translations); err != nil {
116 | return nil, err
117 | }
118 | return translations, nil
119 | }
120 |
121 | func downloadDifficulties(langs []string) (map[string]map[string]string, error) {
122 | resource := component.Resource{Slug: "difficultiesjson"}
123 | translations, err := downloadTranslation(filepath.Join(config.Root, "difficulties.json"), resource)
124 | if err != nil {
125 | return nil, err
126 | }
127 | difficulties := make(map[string]map[string]string)
128 | for _, t := range langs {
129 | var m map[string]string
130 | if err := json.NewDecoder(bytes.NewBufferString(translations[t])).Decode(&m); err != nil {
131 | log.Fatalf("Difficulty error: %s", err)
132 | }
133 | difficulties[t[:2]] = m
134 | }
135 | return difficulties, nil
136 | }
137 |
138 | func saveResults(parser *component.ResourceParser, difficulties map[string]map[string]string) {
139 | for lang, cats := range parser.Categories() {
140 | for _, cat := range cats {
141 | utils.WriteCmp(config.Root, cat)
142 | for _, s := range cat.Subcategories() {
143 | sub := cat.Sub(s)
144 | utils.WriteCmp(config.Root, sub)
145 | for _, d := range sub.DifficultyNames() {
146 | diff := sub.Difficulty(d)
147 | if l, ok := difficulties[lang]; ok {
148 | slug := strings.Join([]string{cat.ID, sub.ID, diff.ID}, "___")
149 | if desc := l[slug]; desc != "" {
150 | diff.Descr = desc
151 | }
152 | }
153 | if check := diff.Checks(); check.HasChildren() {
154 | utils.WriteCmp(config.Root, check)
155 | }
156 | for _, i := range diff.ItemNames() {
157 | utils.WriteCmp(config.Root, diff.Item(i))
158 | }
159 | }
160 | }
161 | }
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/tent/cmd/transifex_upload.go:
--------------------------------------------------------------------------------
1 | // Copyright © 2017 NAME HERE
2 | //
3 | // Licensed under the Apache License, Version 2.0 (the "License");
4 | // you may not use this file except in compliance with the License.
5 | // You may obtain a copy of the License at
6 | //
7 | // http://www.apache.org/licenses/LICENSE-2.0
8 | //
9 | // Unless required by applicable law or agreed to in writing, software
10 | // distributed under the License is distributed on an "AS IS" BASIS,
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | // See the License for the specific language governing permissions and
13 | // limitations under the License.
14 |
15 | package cmd
16 |
17 | import (
18 | "bytes"
19 | "encoding/json"
20 | "log"
21 | "strings"
22 | "time"
23 |
24 | "github.com/securityfirst/tent/transifex"
25 | "github.com/spf13/cobra"
26 | )
27 |
28 | // uploadCmd respresents the upload command
29 | var uploadCmd = &cobra.Command{
30 | Use: "upload",
31 | Short: "Uploads latest contents to Transifex",
32 | Long: `Downloads the lastest version of Tent contents and uploads them to Transifex.`,
33 | Run: uploadRun,
34 | }
35 |
36 | func init() {
37 | transifexCmd.AddCommand(uploadCmd)
38 | }
39 |
40 | func uploadRun(cmd *cobra.Command, args []string) {
41 | if len(args) == 0 {
42 | args = []string{config.Transifex.Language}
43 | }
44 | r, err := newRepo()
45 | if err != nil {
46 | log.Fatalf("Repo error: %s", err)
47 | }
48 | r.Pull()
49 |
50 | locale := r.Locale()
51 | for _, a := range args {
52 | var found bool
53 | for _, l := range locale {
54 | if l == a {
55 | found = true
56 | break
57 | }
58 | }
59 | if !found {
60 | log.Fatalf("Locale not found: %s", a)
61 | }
62 | }
63 |
64 | client := transifex.NewClient(config.Transifex.Project, config.Transifex.Username, config.Transifex.Password)
65 | client.RateLimit(time.Hour, config.Transifex.RequestPerHour)
66 |
67 | resources, err := client.ListResources()
68 | if err != nil {
69 | log.Fatalf("Resource list: %s", err)
70 | }
71 |
72 | var existing = make(map[string]struct{}, len(resources))
73 | for _, r := range resources {
74 | existing[r.Slug] = struct{}{}
75 | }
76 |
77 | var buffer = bytes.NewBuffer(nil)
78 |
79 | for _, a := range args {
80 | for _, cmp := range r.All(a) {
81 | if p := config.Transifex.Filter; p != "" && !strings.HasPrefix(cmp.Path(), p) {
82 | continue
83 | }
84 | buffer.Reset()
85 | resource := cmp.Resource()
86 | json.NewEncoder(buffer).Encode(resource.Content)
87 | var (
88 | resp *transifex.Response
89 | err error
90 | )
91 | if a == config.Transifex.Language {
92 | if _, ok := existing[resource.Slug]; !ok {
93 | resp, err = client.CreateResource(transifex.UploadResourceRequest{
94 | BaseResource: transifex.BaseResource{
95 | Slug: resource.Slug,
96 | Name: resource.Slug + ".json",
97 | I18nType: transifex.KeyValueJson,
98 | },
99 | Content: buffer.String(),
100 | })
101 | } else {
102 | resp, err = client.UpdateResourceContent(resource.Slug, buffer.String())
103 | }
104 | } else {
105 | resp, err = client.UploadTranslationFile(resource.Slug, a, buffer.String())
106 | }
107 |
108 | if err != nil {
109 | log.Printf("Error: %s (%s)", err, cmp.Path())
110 | } else {
111 | log.Printf("%+v (%s)", resp, cmp.Path())
112 | }
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/tent/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "github.com/securityfirst/tent/tent/cmd"
4 |
5 | func main() {
6 | cmd.Execute()
7 | }
8 |
--------------------------------------------------------------------------------
/transifex/client.go:
--------------------------------------------------------------------------------
1 | package transifex
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "io/ioutil"
9 | "net/http"
10 | "strings"
11 | "time"
12 | )
13 |
14 | const KeyValueJson = "KEYVALUEJSON"
15 |
16 | type Client struct {
17 | client *http.Client
18 | tick *time.Ticker
19 | Project Project
20 | }
21 |
22 | func NewClient(project Project, username, password string) Client {
23 | return Client{
24 | client: &http.Client{Transport: auth{username, password}},
25 | Project: project,
26 | }
27 | }
28 |
29 | func (c Client) ListResources() ([]Resource, error) {
30 | resp, err := c.execute("GET", c.Project.list(), nil)
31 | if err != nil {
32 | return nil, err
33 | }
34 | defer resp.Body.Close()
35 |
36 | var resources []Resource
37 | _, err = unmarshal(resp, &resources, "Failed to list resources")
38 | if err != nil {
39 | return nil, err
40 | }
41 | return resources, nil
42 | }
43 |
44 | func (c Client) CreateResource(newResource UploadResourceRequest) (*Response, error) {
45 | data, err := json.Marshal(newResource)
46 | if err != nil {
47 | return nil, err
48 | }
49 | resp, err := c.execute("POST", c.Project.list(), bytes.NewReader(data))
50 | if err != nil {
51 | return nil, err
52 | }
53 |
54 | var r Response
55 | _, err = unmarshal(resp, &r, fmt.Sprintf("Failed to create resource: %s\n", newResource.Slug))
56 | if err != nil {
57 | return nil, err
58 | }
59 |
60 | return &r, nil
61 | }
62 |
63 | func (c Client) UpdateResourceContent(slug, content string) (*Response, error) {
64 | data, err := json.Marshal(map[string]string{"slug": slug, "content": content})
65 | if err != nil {
66 | return nil, err
67 | }
68 | resp, err := c.execute("PUT", c.Project.resource(slug)+"/content/", bytes.NewReader(data))
69 | if err != nil {
70 | return nil, err
71 | }
72 |
73 | var r Response
74 | _, err = unmarshal(resp, &r, fmt.Sprintf("Error updating content of %s", slug))
75 | if err != nil {
76 | return nil, err
77 | }
78 | return &r, nil
79 | }
80 |
81 | func (c Client) ValidateConfiguration() error {
82 | msg := "Error occurred when checking credentials. Please check credentials and network connection"
83 | if _, err := c.SourceLanguage(); err != nil {
84 | return fmt.Errorf(msg)
85 | }
86 | return nil
87 | }
88 |
89 | func (c Client) UploadTranslationFile(slug, langCode, content string) (*Response, error) {
90 | data, err := json.Marshal(map[string]string{"content": content})
91 | if err != nil {
92 | return nil, err
93 | }
94 | resp, err := c.execute("PUT", c.Project.resource(slug)+"/translation/"+langCode+"/", bytes.NewReader(data))
95 | if err != nil {
96 | return nil, err
97 | }
98 |
99 | var r Response
100 | _, err = unmarshal(resp, &r, fmt.Sprintf("Error adding %s translations for %s", langCode, slug))
101 | if err != nil {
102 | return nil, err
103 | }
104 | return nil, err
105 | }
106 |
107 | func (c Client) SourceLanguage() (string, error) {
108 | jsonData, err := c.getJson(c.Project.root(), "Error loading SourceLanguage")
109 | if err != nil {
110 | return "", err
111 | }
112 | lang, has := jsonData.(map[string]interface{})["source_language_code"]
113 | if !has {
114 | return "", fmt.Errorf("An error occurred while reading response. Expected a 'source_language_code' json field:\n%s", jsonData)
115 | }
116 | sourceLang := lang.(string)
117 | if strings.TrimSpace(sourceLang) == "" {
118 | return "", fmt.Errorf("No source language found. This is probably a bug")
119 | }
120 | return sourceLang, nil
121 | }
122 |
123 | func (c Client) Languages() ([]Language, error) {
124 | resp, err := c.execute("GET", fmt.Sprintf("%s/project/%s/languages", ApiUrl, c.Project), nil)
125 |
126 | if err != nil {
127 | return nil, err
128 | }
129 | defer resp.Body.Close()
130 |
131 | data, err := ioutil.ReadAll(resp.Body)
132 | if err != nil {
133 | return nil, err
134 | }
135 | var jsonData []Language
136 | if err = json.Unmarshal(data, &jsonData); err != nil {
137 | return nil, err
138 | }
139 |
140 | return jsonData, nil
141 | }
142 | func (c Client) DownloadTranslations(slug string) (map[string]string, error) {
143 | sourceLang, err := c.SourceLanguage()
144 | if err != nil {
145 | return nil, err
146 | }
147 | fullLangs, err := c.Languages()
148 | if err != nil {
149 | return nil, err
150 | }
151 | langs := make([]string, len(fullLangs)+1)
152 | langs[0] = sourceLang
153 | for i, l := range fullLangs {
154 | langs[i+1] = l.LanguageCode
155 | }
156 |
157 | translations := make(map[string]string, len(langs))
158 | for _, lang := range langs {
159 | url := fmt.Sprintf("%s/project/%s/resource/%s/translation/%s", ApiUrl, c.Project, slug, lang)
160 | data, err := c.getJson(url, "Error downloing translations file")
161 | if err != nil {
162 | return nil, err
163 | }
164 |
165 | translations[lang] = data.(map[string]interface{})["content"].(string)
166 | }
167 | return translations, nil
168 | }
169 |
170 | func (c *Client) RateLimit(t time.Duration, requests int) {
171 | c.tick = time.NewTicker(t / time.Duration(requests))
172 | }
173 |
174 | func (c Client) getJson(url string, errMsg string) (interface{}, error) {
175 | resp, err := c.execute("GET", url, nil)
176 | if err != nil {
177 | return nil, err
178 | }
179 |
180 | jsonData, err := unmarshal(resp, nil, errMsg)
181 | if err != nil {
182 | return nil, err
183 | }
184 |
185 | return jsonData, nil
186 | }
187 |
188 | func (c Client) execute(method string, url string, requestData io.Reader) (*http.Response, error) {
189 | if c.tick != nil {
190 | <-c.tick.C
191 | }
192 | request, err := http.NewRequest(method, url, requestData)
193 | if err != nil {
194 | return nil, err
195 | }
196 | if requestData != nil {
197 | request.Header.Set("Content-Type", "application/json")
198 | }
199 | resp, err := c.client.Do(request)
200 | if err != nil {
201 | return nil, err
202 | }
203 | if resp.StatusCode > 400 {
204 | return nil, fmt.Errorf("Response Code: %v\nResponse Status: %s", resp.StatusCode, resp.Status)
205 | }
206 |
207 | return resp, nil
208 | }
209 |
--------------------------------------------------------------------------------
/transifex/common.go:
--------------------------------------------------------------------------------
1 | package transifex
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io/ioutil"
7 | "net/http"
8 | )
9 |
10 | const ApiUrl = "https://www.transifex.com/api/2"
11 |
12 | type BaseResource struct {
13 | Slug string `json:"slug"`
14 | Name string `json:"name"`
15 | I18nType string `json:"i18n_type"`
16 | Priority string `json:"priority"`
17 | Category string `json:"category"`
18 | }
19 |
20 | type Resource struct {
21 | BaseResource
22 | SourceLanguage string `json:"source_language_code"`
23 | }
24 |
25 | type UploadResourceRequest struct {
26 | BaseResource
27 | Content string `json:"content"`
28 | Accept_translations string `json:"accept_translations"`
29 | }
30 |
31 | type Language struct {
32 | Coordinators []string `json:"coordinators"`
33 | LanguageCode string `json:"language_code"`
34 | Translators []string `json:"translators"`
35 | Reviewers []string `json:"reviewers"`
36 | }
37 |
38 | type Response struct {
39 | Added int `json:"strings_added"`
40 | Updated int `json:"strings_updated"`
41 | Deleted int `json:"strings_delete"`
42 | }
43 |
44 | func (r *Response) UnmarshalJSON(raw []byte) error {
45 | var dst interface{}
46 | if err := json.Unmarshal(raw, &dst); err != nil {
47 | return err
48 | }
49 | switch v := dst.(type) {
50 | case []interface{}:
51 | r.Added = int(v[0].(float64))
52 | r.Updated = int(v[1].(float64))
53 | r.Deleted = int(v[2].(float64))
54 | case map[string]interface{}:
55 | r.Added = int(v["strings_added"].(float64))
56 | r.Updated = int(v["strings_updated"].(float64))
57 | r.Deleted = int(v["strings_delete"].(float64))
58 | default:
59 | return fmt.Errorf("Unkwown type %T", v)
60 | }
61 | return nil
62 | }
63 |
64 | type Project string
65 |
66 | func (p Project) root() string { return fmt.Sprintf("%s/project/%s", ApiUrl, p) }
67 | func (p Project) list() string { return fmt.Sprintf("%s/resources", p.root()) }
68 | func (p Project) resource(id string) string { return fmt.Sprintf("%s/resource/%s", p.root(), id) }
69 |
70 | func unmarshal(resp *http.Response, dst interface{}, errPrefix string) (interface{}, error) {
71 | raw, err := ioutil.ReadAll(resp.Body)
72 | if err != nil {
73 | return nil, err
74 | }
75 | if err := json.Unmarshal(raw, &dst); err != nil {
76 | return nil, fmt.Errorf(errPrefix + "\n\nError:\n" + string(raw))
77 | }
78 | return dst, nil
79 | }
80 |
81 | type auth struct{ Username, Password string }
82 |
83 | func (a auth) RoundTrip(req *http.Request) (*http.Response, error) {
84 | req.SetBasicAuth(a.Username, a.Password)
85 | return http.DefaultTransport.RoundTrip(req)
86 | }
87 |
--------------------------------------------------------------------------------
/utils/idgen.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "regexp"
5 | "strings"
6 | )
7 |
8 | var (
9 | cleanAlphaNum = regexp.MustCompile("[^[:alpha:]\\s\\d_]")
10 | spaceTrim = regexp.MustCompile("\\s+")
11 | manyDash = regexp.MustCompile("-+")
12 | )
13 |
14 | func MakeId(v string) string {
15 | v = cleanAlphaNum.ReplaceAllString(v, " ")
16 | v = spaceTrim.ReplaceAllString(v, "-")
17 | v = manyDash.ReplaceAllString(v, "-")
18 | v = strings.Trim(v, "-")
19 | v = strings.ToLower(v)
20 | return v
21 | }
22 |
--------------------------------------------------------------------------------
/utils/persistence.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "os"
5 | "path/filepath"
6 |
7 | "github.com/securityfirst/tent/component"
8 | )
9 |
10 | func WriteCmp(base string, c component.Component) error {
11 | path := filepath.Join(base, c.Path())
12 | if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
13 | return err
14 | }
15 | f, err := os.Create(path)
16 | if err != nil {
17 | return err
18 | }
19 | if _, err := f.WriteString(c.Contents()); err != nil {
20 | return err
21 | }
22 | return nil
23 | }
24 |
--------------------------------------------------------------------------------