├── README.md
├── auth-api
├── .gitignore
├── Dockerfile
├── Gopkg.lock
├── Gopkg.toml
├── README.md
├── main.go
├── tracing.go
└── user.go
├── frontend
├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .postcssrc.js
├── Dockerfile
├── README.md
├── build
│ ├── build.js
│ ├── check-versions.js
│ ├── dev-client.js
│ ├── dev-server.js
│ ├── utils.js
│ ├── vue-loader.conf.js
│ ├── webpack.base.conf.js
│ ├── webpack.dev.conf.js
│ └── webpack.prod.conf.js
├── config
│ ├── dev.env.js
│ ├── index.js
│ └── prod.env.js
├── index.html
├── package-lock.json
├── package.json
├── src
│ ├── assets
│ │ └── logo.png
│ ├── auth.js
│ ├── components
│ │ ├── App.vue
│ │ ├── AppNav.vue
│ │ ├── Login.vue
│ │ ├── TodoItem.vue
│ │ ├── Todos.vue
│ │ └── common
│ │ │ └── Spinner.vue
│ ├── main.js
│ ├── router
│ │ └── index.js
│ ├── store
│ │ ├── index.js
│ │ ├── mutations.js
│ │ ├── plugins.js
│ │ └── state.js
│ └── zipkin.js
└── static
│ └── .gitkeep
├── images
├── architecture.jpeg
├── cloud9-aws-settings.png
├── cloud9-disable-temp-creds.png
├── cloud9-environments.png
├── cloud9-logo.png
├── cloud9-preferences.png
├── cloud9-step-01.png
├── cloud9-step-02.png
└── cloud9-step-03.png
├── log-message-processor
├── Dockerfile
├── README.md
├── main.py
└── requirements.txt
├── run-your-own-dojo
├── README.md
└── macOS
│ ├── aws-auth-patch.yaml
│ ├── deploy-infra.sh
│ ├── destroy-infra.sh
│ ├── infra
│ ├── main.tf
│ └── variables.tf
│ ├── k8s
│ ├── components
│ │ ├── calico.yaml
│ │ └── ingress-controller.yaml
│ ├── main.tf
│ └── variables.tf
│ ├── main.tf
│ ├── providers.tf
│ ├── terraform.tfvars
│ └── variables.tf
├── todos-api
├── .gitignore
├── Dockerfile
├── README.md
├── package-lock.json
├── package.json
├── routes.js
├── server.js
└── todoController.js
└── users-api
├── .gitignore
├── .mvn
└── wrapper
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── Dockerfile
├── README.md
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── elgris
│ │ └── usersapi
│ │ ├── UsersApiApplication.java
│ │ ├── api
│ │ └── UsersController.java
│ │ ├── configuration
│ │ └── SecurityConfiguration.java
│ │ ├── models
│ │ ├── User.java
│ │ └── UserRole.java
│ │ ├── repository
│ │ └── UserRepository.java
│ │ └── security
│ │ ├── AccessUserFilter.java
│ │ └── JwtAuthenticationFilter.java
└── resources
│ ├── application.properties
│ └── data.sql
└── test
└── java
└── com
└── elgris
└── usersapi
└── UsersApiApplicationTests.java
/auth-api/.gitignore:
--------------------------------------------------------------------------------
1 | vendor
2 | auth-api
--------------------------------------------------------------------------------
/auth-api/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.9-alpine
2 |
3 | EXPOSE 8081
4 |
5 | WORKDIR /go/src/app
6 | RUN apk --no-cache add curl git && \
7 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
8 |
9 | COPY . .
10 | RUN dep ensure
11 |
12 | RUN go build -o auth-api
13 |
14 | CMD /go/src/app/auth-api
15 |
16 |
--------------------------------------------------------------------------------
/auth-api/Gopkg.lock:
--------------------------------------------------------------------------------
1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
2 |
3 |
4 | [[projects]]
5 | name = "github.com/dgrijalva/jwt-go"
6 | packages = ["."]
7 | revision = "dbeaa9332f19a944acb5736b4456cfcc02140e29"
8 | version = "v3.1.0"
9 |
10 | [[projects]]
11 | name = "github.com/labstack/echo"
12 | packages = [
13 | ".",
14 | "middleware"
15 | ]
16 | revision = "b338075a0fc6e1a0683dbf03d09b4957a289e26f"
17 | version = "3.2.6"
18 |
19 | [[projects]]
20 | name = "github.com/labstack/gommon"
21 | packages = [
22 | "bytes",
23 | "color",
24 | "log",
25 | "random"
26 | ]
27 | revision = "57409ada9da0f2afad6664c49502f8c50fbd8476"
28 | version = "0.2.3"
29 |
30 | [[projects]]
31 | name = "github.com/mattn/go-colorable"
32 | packages = ["."]
33 | revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072"
34 | version = "v0.0.9"
35 |
36 | [[projects]]
37 | name = "github.com/mattn/go-isatty"
38 | packages = ["."]
39 | revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
40 | version = "v0.0.3"
41 |
42 | [[projects]]
43 | branch = "master"
44 | name = "github.com/openzipkin/zipkin-go"
45 | packages = [
46 | ".",
47 | "idgenerator",
48 | "middleware/http",
49 | "model",
50 | "propagation",
51 | "propagation/b3",
52 | "reporter",
53 | "reporter/http"
54 | ]
55 | revision = "3741243b287094fda649c7f0fa74bd51f37dc122"
56 |
57 | [[projects]]
58 | branch = "master"
59 | name = "github.com/valyala/bytebufferpool"
60 | packages = ["."]
61 | revision = "e746df99fe4a3986f4d4f79e13c1e0117ce9c2f7"
62 |
63 | [[projects]]
64 | branch = "master"
65 | name = "github.com/valyala/fasttemplate"
66 | packages = ["."]
67 | revision = "dcecefd839c4193db0d35b88ec65b4c12d360ab0"
68 |
69 | [[projects]]
70 | branch = "master"
71 | name = "golang.org/x/crypto"
72 | packages = [
73 | "acme",
74 | "acme/autocert"
75 | ]
76 | revision = "49796115aa4b964c318aad4f3084fdb41e9aa067"
77 |
78 | [[projects]]
79 | branch = "master"
80 | name = "golang.org/x/net"
81 | packages = ["context"]
82 | revision = "cbe0f9307d0156177f9dd5dc85da1a31abc5f2fb"
83 |
84 | [[projects]]
85 | branch = "master"
86 | name = "golang.org/x/sys"
87 | packages = ["unix"]
88 | revision = "c1138c84af3a9927aee1a1b8b7ce06c9b7ea52bc"
89 |
90 | [[projects]]
91 | name = "google.golang.org/grpc"
92 | packages = ["metadata"]
93 | revision = "8e4536a86ab602859c20df5ebfd0bd4228d08655"
94 | version = "v1.10.0"
95 |
96 | [solve-meta]
97 | analyzer-name = "dep"
98 | analyzer-version = 1
99 | inputs-digest = "e4ae9d27bce5a7d452ffa8d5a8cffe562fe7c8853f59a1dc12f64e73cd95013a"
100 | solver-name = "gps-cdcl"
101 | solver-version = 1
102 |
--------------------------------------------------------------------------------
/auth-api/Gopkg.toml:
--------------------------------------------------------------------------------
1 |
2 | # Gopkg.toml example
3 | #
4 | # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
5 | # for detailed Gopkg.toml documentation.
6 | #
7 | # required = ["github.com/user/thing/cmd/thing"]
8 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
9 | #
10 | # [[constraint]]
11 | # name = "github.com/user/project"
12 | # version = "1.0.0"
13 | #
14 | # [[constraint]]
15 | # name = "github.com/user/project2"
16 | # branch = "dev"
17 | # source = "github.com/myfork/project2"
18 | #
19 | # [[override]]
20 | # name = "github.com/x/y"
21 | # version = "2.4.0"
22 |
23 |
24 | [[constraint]]
25 | name = "github.com/dgrijalva/jwt-go"
26 | version = "3.1.0"
27 |
28 | [[constraint]]
29 | name = "github.com/labstack/echo"
30 | version = "3.2.2"
31 |
32 | [[constraint]]
33 | branch = "master"
34 | name = "github.com/openzipkin/zipkin-go"
--------------------------------------------------------------------------------
/auth-api/README.md:
--------------------------------------------------------------------------------
1 | # auth-api
2 |
3 | This part of the exercise is responsible for authentication. It is written in Go and tested with Go1.9.
4 |
5 | It provides a single useful API endpoint `POST /login` that takes a simple JSON object and
6 | returns an access token in case of successful authentication.
7 |
8 | The JSON object structure is following:
9 | ```json
10 | {
11 | "username": "admin",
12 | "password": "admin",
13 | }
14 | ```
15 |
16 | ## Prerequisites
17 | [Users API](/users-api) must be running, because `auth-api` fetches user data from it (yes, it is a little bit contrived, but anyways it's OVERENGINEERING!)
18 |
19 | ## Configuration
20 |
21 | The service scans environment for variables:
22 | - `AUTH_API_PORT` - the port the service takes.
23 | - `USERS_API_ADDRESS` - base URL of [Users API](/users-api).
24 | - `JWT_SECRET` - secret value for JWT generator. Must be shared amongst all components.
25 |
26 | Following users are hardcoded for you:
27 |
28 | | Username | Password |
29 | |-----------|-----------|
30 | | admin | admin |
31 | | johnd | foo |
32 | | janed | ddd |
33 |
34 | ## Building and running
35 |
36 | 1. Update the dependencies with [glide](https://github.com/Masterminds/glide)
37 | ```
38 | glide up
39 | ```
40 | 2. Compile a binary and then run it
41 | ```
42 | go build
43 | AUTH_API_PORT=8000 USERS_API_ADDRESS=http://users-api:8082 JWT_SECRET=foo ./auth-api
44 | ```
45 |
46 | ## Usage
47 |
48 | ```
49 | curl -X POST 127.0.0.1:8000/login -d '{"username": "admin","password": "admin"}'
50 | ```
51 |
--------------------------------------------------------------------------------
/auth-api/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "log"
6 | "net/http"
7 | "os"
8 | "time"
9 |
10 | jwt "github.com/dgrijalva/jwt-go"
11 | "github.com/labstack/echo"
12 | "github.com/labstack/echo/middleware"
13 | gommonlog "github.com/labstack/gommon/log"
14 | )
15 |
16 | var (
17 | // ErrHttpGenericMessage that is returned in general case, details should be logged in such case
18 | ErrHttpGenericMessage = echo.NewHTTPError(http.StatusInternalServerError, "something went wrong, please try again later")
19 |
20 | // ErrWrongCredentials indicates that login attempt failed because of incorrect login or password
21 | ErrWrongCredentials = echo.NewHTTPError(http.StatusUnauthorized, "username or password is invalid")
22 |
23 | jwtSecret = "myfancysecret"
24 | )
25 |
26 | func main() {
27 | hostport := ":" + os.Getenv("AUTH_API_PORT")
28 | userAPIAddress := os.Getenv("USERS_API_ADDRESS")
29 |
30 | envJwtSecret := os.Getenv("JWT_SECRET")
31 | if len(envJwtSecret) != 0 {
32 | jwtSecret = envJwtSecret
33 | }
34 |
35 | userService := UserService{
36 | Client: http.DefaultClient,
37 | UserAPIAddress: userAPIAddress,
38 | AllowedUserHashes: map[string]interface{}{
39 | "admin_admin": nil,
40 | "johnd_foo": nil,
41 | "janed_ddd": nil,
42 | },
43 | }
44 |
45 | e := echo.New()
46 | e.Logger.SetLevel(gommonlog.INFO)
47 |
48 | if zipkinURL := os.Getenv("ZIPKIN_URL"); len(zipkinURL) != 0 {
49 | e.Logger.Infof("init tracing to Zipkit at %s", zipkinURL)
50 |
51 | if tracedMiddleware, tracedClient, err := initTracing(zipkinURL); err == nil {
52 | e.Use(echo.WrapMiddleware(tracedMiddleware))
53 | userService.Client = tracedClient
54 | } else {
55 | e.Logger.Infof("Zipkin tracer init failed: %s", err.Error())
56 | }
57 | } else {
58 | e.Logger.Infof("Zipkin URL was not provided, tracing is not initialised")
59 | }
60 |
61 | e.Use(middleware.Logger())
62 | e.Use(middleware.Recover())
63 | e.Use(middleware.CORS())
64 |
65 | // Route => handler
66 | e.GET("/version", func(c echo.Context) error {
67 | return c.String(http.StatusOK, "Auth API, written in Go\n")
68 | })
69 |
70 | e.POST("/login", getLoginHandler(userService))
71 |
72 | // Start server
73 | e.Logger.Fatal(e.Start(hostport))
74 | }
75 |
76 | type LoginRequest struct {
77 | Username string `json:"username"`
78 | Password string `json:"password"`
79 | }
80 |
81 | func getLoginHandler(userService UserService) echo.HandlerFunc {
82 | f := func(c echo.Context) error {
83 | requestData := LoginRequest{}
84 | decoder := json.NewDecoder(c.Request().Body)
85 | if err := decoder.Decode(&requestData); err != nil {
86 | log.Printf("could not read credentials from POST body: %s", err.Error())
87 | return ErrHttpGenericMessage
88 | }
89 |
90 | ctx := c.Request().Context()
91 | user, err := userService.Login(ctx, requestData.Username, requestData.Password)
92 | if err != nil {
93 | if err != ErrWrongCredentials {
94 | log.Printf("could not authorize user '%s': %s", requestData.Username, err.Error())
95 | return ErrHttpGenericMessage
96 | }
97 |
98 | return ErrWrongCredentials
99 | }
100 | token := jwt.New(jwt.SigningMethodHS256)
101 |
102 | // Set claims
103 | claims := token.Claims.(jwt.MapClaims)
104 | claims["username"] = user.Username
105 | claims["firstname"] = user.FirstName
106 | claims["lastname"] = user.LastName
107 | claims["role"] = user.Role
108 | claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
109 |
110 | // Generate encoded token and send it as response.
111 | t, err := token.SignedString([]byte(jwtSecret))
112 | if err != nil {
113 | log.Printf("could not generate a JWT token: %s", err.Error())
114 | return ErrHttpGenericMessage
115 | }
116 |
117 | return c.JSON(http.StatusOK, map[string]string{
118 | "accessToken": t,
119 | })
120 | }
121 |
122 | return echo.HandlerFunc(f)
123 | }
124 |
--------------------------------------------------------------------------------
/auth-api/tracing.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net/http"
5 |
6 | zipkin "github.com/openzipkin/zipkin-go"
7 | zipkinhttp "github.com/openzipkin/zipkin-go/middleware/http"
8 | zipkinhttpreporter "github.com/openzipkin/zipkin-go/reporter/http"
9 | )
10 |
11 | type TracedClient struct {
12 | client *zipkinhttp.Client
13 | }
14 |
15 | func (c *TracedClient) Do(req *http.Request) (*http.Response, error) {
16 | name := req.Method + " " + req.RequestURI
17 | return c.client.DoWithAppSpan(req, name)
18 | }
19 |
20 | func initTracing(zipkinURL string) (func(http.Handler) http.Handler, *TracedClient, error) {
21 | reporter := zipkinhttpreporter.NewReporter(zipkinURL)
22 |
23 | endpoint, err := zipkin.NewEndpoint("auth-api", "")
24 | if err != nil {
25 | return nil, nil, err
26 | }
27 |
28 | tracer, err := zipkin.NewTracer(reporter,
29 | zipkin.WithLocalEndpoint(endpoint),
30 | zipkin.WithSharedSpans(false))
31 | if err != nil {
32 | return nil, nil, err
33 | }
34 |
35 | // create global zipkin http server middleware
36 | serverMiddleware := zipkinhttp.NewServerMiddleware(
37 | tracer, zipkinhttp.TagResponseSize(true),
38 | )
39 |
40 | // create global zipkin traced http client
41 | client, err := zipkinhttp.NewClient(tracer, zipkinhttp.ClientTrace(true))
42 | if err != nil {
43 | return nil, nil, err
44 | }
45 |
46 | return serverMiddleware, &TracedClient{client}, nil
47 | }
48 |
--------------------------------------------------------------------------------
/auth-api/user.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "fmt"
7 | "io/ioutil"
8 | "net/http"
9 |
10 | jwt "github.com/dgrijalva/jwt-go"
11 | )
12 |
13 | var allowedUserHashes = map[string]interface{}{
14 | "admin_admin": nil,
15 | "johnd_foo": nil,
16 | "janed_ddd": nil,
17 | }
18 |
19 | type User struct {
20 | Username string `json:"username"`
21 | FirstName string `json:"firstname"`
22 | LastName string `json:"lastname"`
23 | Role string `json:"role"`
24 | }
25 |
26 | type HTTPDoer interface {
27 | Do(req *http.Request) (*http.Response, error)
28 | }
29 |
30 | type UserService struct {
31 | Client HTTPDoer
32 | UserAPIAddress string
33 | AllowedUserHashes map[string]interface{}
34 | }
35 |
36 | func (h *UserService) Login(ctx context.Context, username, password string) (User, error) {
37 | user, err := h.getUser(ctx, username)
38 | if err != nil {
39 | return user, err
40 | }
41 |
42 | userKey := fmt.Sprintf("%s_%s", username, password)
43 |
44 | if _, ok := h.AllowedUserHashes[userKey]; !ok {
45 | return user, ErrWrongCredentials // this is BAD, business logic layer must not return HTTP-specific errors
46 | }
47 |
48 | return user, nil
49 | }
50 |
51 | func (h *UserService) getUser(ctx context.Context, username string) (User, error) {
52 | var user User
53 |
54 | token, err := h.getUserAPIToken(username)
55 | if err != nil {
56 | return user, err
57 | }
58 | url := fmt.Sprintf("%s/users/%s", h.UserAPIAddress, username)
59 | req, _ := http.NewRequest("GET", url, nil)
60 | req.Header.Add("Authorization", "Bearer "+token)
61 |
62 | req = req.WithContext(ctx)
63 |
64 | resp, err := h.Client.Do(req)
65 | if err != nil {
66 | return user, err
67 | }
68 |
69 | defer resp.Body.Close()
70 | bodyBytes, err := ioutil.ReadAll(resp.Body)
71 | if err != nil {
72 | return user, err
73 | }
74 |
75 | if resp.StatusCode < 200 || resp.StatusCode >= 300 {
76 | return user, fmt.Errorf("could not get user data: %s", string(bodyBytes))
77 | }
78 |
79 | err = json.Unmarshal(bodyBytes, &user)
80 |
81 | return user, err
82 | }
83 |
84 | func (h *UserService) getUserAPIToken(username string) (string, error) {
85 | token := jwt.New(jwt.SigningMethodHS256)
86 | claims := token.Claims.(jwt.MapClaims)
87 | claims["username"] = username
88 | claims["scope"] = "read"
89 | return token.SignedString([]byte(jwtSecret))
90 | }
91 |
--------------------------------------------------------------------------------
/frontend/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env", {
4 | "modules": false,
5 | "targets": {
6 | "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
7 | }
8 | }],
9 | "stage-2"
10 | ],
11 | "plugins": ["transform-runtime"],
12 | "env": {
13 | "test": {
14 | "presets": ["env", "stage-2"],
15 | "plugins": ["istanbul"]
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/frontend/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/frontend/.eslintignore:
--------------------------------------------------------------------------------
1 | build/*.js
2 | config/*.js
3 |
--------------------------------------------------------------------------------
/frontend/.eslintrc.js:
--------------------------------------------------------------------------------
1 | // http://eslint.org/docs/user-guide/configuring
2 |
3 | module.exports = {
4 | root: true,
5 | parser: 'babel-eslint',
6 | parserOptions: {
7 | sourceType: 'module'
8 | },
9 | env: {
10 | browser: true,
11 | },
12 | // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
13 | extends: 'standard',
14 | // required to lint *.vue files
15 | plugins: [
16 | 'html'
17 | ],
18 | // add your custom rules here
19 | 'rules': {
20 | // allow paren-less arrow functions
21 | 'arrow-parens': 0,
22 | // allow async-await
23 | 'generator-star-spacing': 0,
24 | // allow debugger during development
25 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/frontend/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules/
3 | dist/
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Editor directories and files
9 | .idea
10 | *.suo
11 | *.ntvs*
12 | *.njsproj
13 | *.sln
14 |
--------------------------------------------------------------------------------
/frontend/.postcssrc.js:
--------------------------------------------------------------------------------
1 | // https://github.com/michael-ciniawsky/postcss-load-config
2 |
3 | module.exports = {
4 | "plugins": {
5 | // to edit target browsers: use "browserslist" field in package.json
6 | "autoprefixer": {}
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/frontend/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:8-alpine
2 |
3 | EXPOSE 8080
4 |
5 | WORKDIR /usr/src/app
6 |
7 | COPY package.json ./
8 | RUN npm install
9 |
10 | COPY . .
11 |
12 | CMD ["sh", "-c", "npm start" ]
--------------------------------------------------------------------------------
/frontend/README.md:
--------------------------------------------------------------------------------
1 | # frontend
2 |
3 | UI for sample distributed TODO app build with VueJS
4 |
5 | ## Configuration
6 | - `PORT` - a port the application binds to
7 | - `AUTH_API_ADDRESS` - address of `auth-api` for authentication
8 | - `TODOS_API_ADDRESS` - address of `todos-api` for TODO CRUD
9 |
10 | ## Building and running
11 |
12 | ``` bash
13 | # install dependencies
14 | npm install
15 |
16 | # serve with hot reload at localhost:8080
17 | npm run dev
18 |
19 | # build for production with minification
20 | npm run build
21 |
22 | # build for production and view the bundle analyzer report
23 | npm run build --report
24 | ```
25 |
26 | For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
27 |
--------------------------------------------------------------------------------
/frontend/build/build.js:
--------------------------------------------------------------------------------
1 | require('./check-versions')()
2 |
3 | process.env.NODE_ENV = 'production'
4 |
5 | var ora = require('ora')
6 | var rm = require('rimraf')
7 | var path = require('path')
8 | var chalk = require('chalk')
9 | var webpack = require('webpack')
10 | var config = require('../config')
11 | var webpackConfig = require('./webpack.prod.conf')
12 |
13 | var spinner = ora('building for production...')
14 | spinner.start()
15 |
16 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
17 | if (err) throw err
18 | webpack(webpackConfig, function (err, stats) {
19 | spinner.stop()
20 | if (err) throw err
21 | process.stdout.write(stats.toString({
22 | colors: true,
23 | modules: false,
24 | children: false,
25 | chunks: false,
26 | chunkModules: false
27 | }) + '\n\n')
28 |
29 | console.log(chalk.cyan(' Build complete.\n'))
30 | console.log(chalk.yellow(
31 | ' Tip: built files are meant to be served over an HTTP server.\n' +
32 | ' Opening index.html over file:// won\'t work.\n'
33 | ))
34 | })
35 | })
36 |
--------------------------------------------------------------------------------
/frontend/build/check-versions.js:
--------------------------------------------------------------------------------
1 | var chalk = require('chalk')
2 | var semver = require('semver')
3 | var packageConfig = require('../package.json')
4 | var shell = require('shelljs')
5 | function exec (cmd) {
6 | return require('child_process').execSync(cmd).toString().trim()
7 | }
8 |
9 | var versionRequirements = [
10 | {
11 | name: 'node',
12 | currentVersion: semver.clean(process.version),
13 | versionRequirement: packageConfig.engines.node
14 | },
15 | ]
16 |
17 | if (shell.which('npm')) {
18 | versionRequirements.push({
19 | name: 'npm',
20 | currentVersion: exec('npm --version'),
21 | versionRequirement: packageConfig.engines.npm
22 | })
23 | }
24 |
25 | module.exports = function () {
26 | var warnings = []
27 | for (var i = 0; i < versionRequirements.length; i++) {
28 | var mod = versionRequirements[i]
29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
30 | warnings.push(mod.name + ': ' +
31 | chalk.red(mod.currentVersion) + ' should be ' +
32 | chalk.green(mod.versionRequirement)
33 | )
34 | }
35 | }
36 |
37 | if (warnings.length) {
38 | console.log('')
39 | console.log(chalk.yellow('To use this template, you must update following to modules:'))
40 | console.log()
41 | for (var i = 0; i < warnings.length; i++) {
42 | var warning = warnings[i]
43 | console.log(' ' + warning)
44 | }
45 | console.log()
46 | process.exit(1)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/frontend/build/dev-client.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | require('eventsource-polyfill')
3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
4 |
5 | hotClient.subscribe(function (event) {
6 | if (event.action === 'reload') {
7 | window.location.reload()
8 | }
9 | })
10 |
--------------------------------------------------------------------------------
/frontend/build/dev-server.js:
--------------------------------------------------------------------------------
1 | require('./check-versions')()
2 |
3 | var config = require('../config')
4 | if (!process.env.NODE_ENV) {
5 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
6 | }
7 |
8 | var opn = require('opn')
9 | var path = require('path')
10 | var express = require('express')
11 | var webpack = require('webpack')
12 | var proxyMiddleware = require('http-proxy-middleware')
13 | var webpackConfig = require('./webpack.dev.conf')
14 |
15 | // default port where dev server listens for incoming traffic
16 | var port = process.env.PORT || config.dev.port || 8080
17 | // automatically open browser, if not set will be false
18 | var autoOpenBrowser = !!config.dev.autoOpenBrowser
19 | // Define HTTP proxies to your custom API backend
20 | // https://github.com/chimurai/http-proxy-middleware
21 | var proxyTable = config.dev.proxyTable
22 |
23 | var app = express()
24 | var compiler = webpack(webpackConfig)
25 |
26 | var devMiddleware = require('webpack-dev-middleware')(compiler, {
27 | publicPath: webpackConfig.output.publicPath,
28 | quiet: true
29 | })
30 |
31 | var hotMiddleware = require('webpack-hot-middleware')(compiler, {
32 | log: false,
33 | heartbeat: 2000
34 | })
35 | // force page reload when html-webpack-plugin template changes
36 | compiler.plugin('compilation', function (compilation) {
37 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
38 | hotMiddleware.publish({ action: 'reload' })
39 | cb()
40 | })
41 | })
42 |
43 | // proxy api requests
44 | Object.keys(proxyTable).forEach(function (context) {
45 | var options = proxyTable[context]
46 | if (typeof options === 'string') {
47 | options = { target: options }
48 | }
49 | app.use(proxyMiddleware(options.filter || context, options))
50 | })
51 |
52 | // handle fallback for HTML5 history API
53 | app.use(require('connect-history-api-fallback')())
54 |
55 | // serve webpack bundle output
56 | app.use(devMiddleware)
57 |
58 | // enable hot-reload and state-preserving
59 | // compilation error display
60 | app.use(hotMiddleware)
61 |
62 | // serve pure static assets
63 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
64 | app.use(staticPath, express.static('./static'))
65 |
66 | var uri = 'http://127.0.0.1:' + port
67 |
68 | var _resolve
69 | var readyPromise = new Promise(resolve => {
70 | _resolve = resolve
71 | })
72 |
73 | console.log('> Starting dev server...')
74 | devMiddleware.waitUntilValid(() => {
75 | console.log('> Listening at ' + uri + '\n')
76 | // when env is testing, don't need open it
77 | if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
78 | opn(uri)
79 | }
80 | _resolve()
81 | })
82 |
83 | var server = app.listen(port)
84 |
85 | module.exports = {
86 | ready: readyPromise,
87 | close: () => {
88 | server.close()
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/frontend/build/utils.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var config = require('../config')
3 | var ExtractTextPlugin = require('extract-text-webpack-plugin')
4 |
5 | exports.assetsPath = function (_path) {
6 | var assetsSubDirectory = process.env.NODE_ENV === 'production'
7 | ? config.build.assetsSubDirectory
8 | : config.dev.assetsSubDirectory
9 | return path.posix.join(assetsSubDirectory, _path)
10 | }
11 |
12 | exports.cssLoaders = function (options) {
13 | options = options || {}
14 |
15 | var cssLoader = {
16 | loader: 'css-loader',
17 | options: {
18 | minimize: process.env.NODE_ENV === 'production',
19 | sourceMap: options.sourceMap
20 | }
21 | }
22 |
23 | // generate loader string to be used with extract text plugin
24 | function generateLoaders (loader, loaderOptions) {
25 | var loaders = [cssLoader]
26 | if (loader) {
27 | loaders.push({
28 | loader: loader + '-loader',
29 | options: Object.assign({}, loaderOptions, {
30 | sourceMap: options.sourceMap
31 | })
32 | })
33 | }
34 |
35 | // Extract CSS when that option is specified
36 | // (which is the case during production build)
37 | if (options.extract) {
38 | return ExtractTextPlugin.extract({
39 | use: loaders,
40 | fallback: 'vue-style-loader'
41 | })
42 | } else {
43 | return ['vue-style-loader'].concat(loaders)
44 | }
45 | }
46 |
47 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html
48 | return {
49 | css: generateLoaders(),
50 | postcss: generateLoaders(),
51 | less: generateLoaders('less'),
52 | sass: generateLoaders('sass', { indentedSyntax: true }),
53 | scss: generateLoaders('sass'),
54 | stylus: generateLoaders('stylus'),
55 | styl: generateLoaders('stylus')
56 | }
57 | }
58 |
59 | // Generate loaders for standalone style files (outside of .vue)
60 | exports.styleLoaders = function (options) {
61 | var output = []
62 | var loaders = exports.cssLoaders(options)
63 | for (var extension in loaders) {
64 | var loader = loaders[extension]
65 | output.push({
66 | test: new RegExp('\\.' + extension + '$'),
67 | use: loader
68 | })
69 | }
70 | return output
71 | }
72 |
--------------------------------------------------------------------------------
/frontend/build/vue-loader.conf.js:
--------------------------------------------------------------------------------
1 | var utils = require('./utils')
2 | var config = require('../config')
3 | var isProduction = process.env.NODE_ENV === 'production'
4 |
5 | module.exports = {
6 | loaders: utils.cssLoaders({
7 | sourceMap: isProduction
8 | ? config.build.productionSourceMap
9 | : config.dev.cssSourceMap,
10 | extract: isProduction
11 | }),
12 | transformToRequire: {
13 | video: 'src',
14 | source: 'src',
15 | img: 'src',
16 | image: 'xlink:href'
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/frontend/build/webpack.base.conf.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var utils = require('./utils')
3 | var config = require('../config')
4 | var vueLoaderConfig = require('./vue-loader.conf')
5 |
6 | function resolve (dir) {
7 | return path.join(__dirname, '..', dir)
8 | }
9 |
10 | module.exports = {
11 | entry: {
12 | app: './src/main.js'
13 | },
14 | output: {
15 | path: config.build.assetsRoot,
16 | filename: '[name].js',
17 | publicPath: process.env.NODE_ENV === 'production'
18 | ? config.build.assetsPublicPath
19 | : config.dev.assetsPublicPath
20 | },
21 | resolve: {
22 | extensions: ['.js', '.vue', '.json'],
23 | alias: {
24 | 'vue$': 'vue/dist/vue.esm.js',
25 | '@': resolve('src')
26 | }
27 | },
28 | module: {
29 | rules: [
30 | {
31 | test: /\.(js|vue)$/,
32 | loader: 'eslint-loader',
33 | enforce: 'pre',
34 | include: [resolve('src'), resolve('test')],
35 | options: {
36 | formatter: require('eslint-friendly-formatter')
37 | }
38 | },
39 | {
40 | test: /\.vue$/,
41 | loader: 'vue-loader',
42 | options: vueLoaderConfig
43 | },
44 | {
45 | test: /\.js$/,
46 | loader: 'babel-loader',
47 | include: [resolve('src'), resolve('test')]
48 | },
49 | {
50 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
51 | loader: 'url-loader',
52 | options: {
53 | limit: 10000,
54 | name: utils.assetsPath('img/[name].[hash:7].[ext]')
55 | }
56 | },
57 | {
58 | test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
59 | loader: 'url-loader',
60 | options: {
61 | limit: 10000,
62 | name: utils.assetsPath('media/[name].[hash:7].[ext]')
63 | }
64 | },
65 | {
66 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
67 | loader: 'url-loader',
68 | options: {
69 | limit: 10000,
70 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
71 | }
72 | }
73 | ]
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/frontend/build/webpack.dev.conf.js:
--------------------------------------------------------------------------------
1 | var utils = require('./utils')
2 | var webpack = require('webpack')
3 | var config = require('../config')
4 | var merge = require('webpack-merge')
5 | var baseWebpackConfig = require('./webpack.base.conf')
6 | var HtmlWebpackPlugin = require('html-webpack-plugin')
7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
8 |
9 | // add hot-reload related code to entry chunks
10 | Object.keys(baseWebpackConfig.entry).forEach(function (name) {
11 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
12 | })
13 |
14 | module.exports = merge(baseWebpackConfig, {
15 | module: {
16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
17 | },
18 | // cheap-module-eval-source-map is faster for development
19 | devtool: '#cheap-module-eval-source-map',
20 | plugins: [
21 | new webpack.DefinePlugin({
22 | 'process.env': config.dev.env
23 | }),
24 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
25 | new webpack.HotModuleReplacementPlugin(),
26 | new webpack.NoEmitOnErrorsPlugin(),
27 | // https://github.com/ampedandwired/html-webpack-plugin
28 | new HtmlWebpackPlugin({
29 | filename: 'index.html',
30 | template: 'index.html',
31 | inject: true
32 | }),
33 | new FriendlyErrorsPlugin()
34 | ]
35 | })
36 |
--------------------------------------------------------------------------------
/frontend/build/webpack.prod.conf.js:
--------------------------------------------------------------------------------
1 | var path = require('path')
2 | var utils = require('./utils')
3 | var webpack = require('webpack')
4 | var config = require('../config')
5 | var merge = require('webpack-merge')
6 | var baseWebpackConfig = require('./webpack.base.conf')
7 | var CopyWebpackPlugin = require('copy-webpack-plugin')
8 | var HtmlWebpackPlugin = require('html-webpack-plugin')
9 | var ExtractTextPlugin = require('extract-text-webpack-plugin')
10 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
11 |
12 | var env = config.build.env
13 |
14 | var webpackConfig = merge(baseWebpackConfig, {
15 | module: {
16 | rules: utils.styleLoaders({
17 | sourceMap: config.build.productionSourceMap,
18 | extract: true
19 | })
20 | },
21 | devtool: config.build.productionSourceMap ? '#source-map' : false,
22 | output: {
23 | path: config.build.assetsRoot,
24 | filename: utils.assetsPath('js/[name].[chunkhash].js'),
25 | chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
26 | },
27 | plugins: [
28 | // http://vuejs.github.io/vue-loader/en/workflow/production.html
29 | new webpack.DefinePlugin({
30 | 'process.env': env
31 | }),
32 | new webpack.optimize.UglifyJsPlugin({
33 | compress: {
34 | warnings: false
35 | },
36 | sourceMap: true
37 | }),
38 | // extract css into its own file
39 | new ExtractTextPlugin({
40 | filename: utils.assetsPath('css/[name].[contenthash].css')
41 | }),
42 | // Compress extracted CSS. We are using this plugin so that possible
43 | // duplicated CSS from different components can be deduped.
44 | new OptimizeCSSPlugin({
45 | cssProcessorOptions: {
46 | safe: true
47 | }
48 | }),
49 | // generate dist index.html with correct asset hash for caching.
50 | // you can customize output by editing /index.html
51 | // see https://github.com/ampedandwired/html-webpack-plugin
52 | new HtmlWebpackPlugin({
53 | filename: config.build.index,
54 | template: 'index.html',
55 | inject: true,
56 | minify: {
57 | removeComments: true,
58 | collapseWhitespace: true,
59 | removeAttributeQuotes: true
60 | // more options:
61 | // https://github.com/kangax/html-minifier#options-quick-reference
62 | },
63 | // necessary to consistently work with multiple chunks via CommonsChunkPlugin
64 | chunksSortMode: 'dependency'
65 | }),
66 | // split vendor js into its own file
67 | new webpack.optimize.CommonsChunkPlugin({
68 | name: 'vendor',
69 | minChunks: function (module, count) {
70 | // any required modules inside node_modules are extracted to vendor
71 | return (
72 | module.resource &&
73 | /\.js$/.test(module.resource) &&
74 | module.resource.indexOf(
75 | path.join(__dirname, '../node_modules')
76 | ) === 0
77 | )
78 | }
79 | }),
80 | // extract webpack runtime and module manifest to its own file in order to
81 | // prevent vendor hash from being updated whenever app bundle is updated
82 | new webpack.optimize.CommonsChunkPlugin({
83 | name: 'manifest',
84 | chunks: ['vendor']
85 | }),
86 | // copy custom static assets
87 | new CopyWebpackPlugin([
88 | {
89 | from: path.resolve(__dirname, '../static'),
90 | to: config.build.assetsSubDirectory,
91 | ignore: ['.*']
92 | }
93 | ])
94 | ]
95 | })
96 |
97 | if (config.build.productionGzip) {
98 | var CompressionWebpackPlugin = require('compression-webpack-plugin')
99 |
100 | webpackConfig.plugins.push(
101 | new CompressionWebpackPlugin({
102 | asset: '[path].gz[query]',
103 | algorithm: 'gzip',
104 | test: new RegExp(
105 | '\\.(' +
106 | config.build.productionGzipExtensions.join('|') +
107 | ')$'
108 | ),
109 | threshold: 10240,
110 | minRatio: 0.8
111 | })
112 | )
113 | }
114 |
115 | if (config.build.bundleAnalyzerReport) {
116 | var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
117 | webpackConfig.plugins.push(new BundleAnalyzerPlugin())
118 | }
119 |
120 | module.exports = webpackConfig
121 |
--------------------------------------------------------------------------------
/frontend/config/dev.env.js:
--------------------------------------------------------------------------------
1 | var merge = require('webpack-merge')
2 | var prodEnv = require('./prod.env')
3 |
4 | module.exports = merge(prodEnv, {
5 | NODE_ENV: '"development"'
6 | })
7 |
--------------------------------------------------------------------------------
/frontend/config/index.js:
--------------------------------------------------------------------------------
1 | // see http://vuejs-templates.github.io/webpack for documentation.
2 | var path = require('path')
3 |
4 | module.exports = {
5 | build: {
6 | env: require('./prod.env'),
7 | index: path.resolve(__dirname, '../dist/index.html'),
8 | assetsRoot: path.resolve(__dirname, '../dist'),
9 | assetsSubDirectory: 'static',
10 | assetsPublicPath: '/',
11 | productionSourceMap: true,
12 | // Gzip off by default as many popular static hosts such as
13 | // Surge or Netlify already gzip all static assets for you.
14 | // Before setting to `true`, make sure to:
15 | // npm install --save-dev compression-webpack-plugin
16 | productionGzip: false,
17 | productionGzipExtensions: ['js', 'css'],
18 | // Run the build command with an extra argument to
19 | // View the bundle analyzer report after build finishes:
20 | // `npm run build --report`
21 | // Set to `true` or `false` to always turn it on or off
22 | bundleAnalyzerReport: process.env.npm_config_report
23 | },
24 | dev: {
25 | env: require('./dev.env'),
26 | port: process.env.PORT,
27 | autoOpenBrowser: false,
28 | assetsSubDirectory: 'static',
29 | assetsPublicPath: '/',
30 | proxyTable: {
31 | '/login': {
32 | target: process.env.AUTH_API_ADDRESS || 'http://127.0.0.1:8081',
33 | secure: false
34 | },
35 | '/todos': {
36 | target: process.env.TODOS_API_ADDRESS || 'http://127.0.0.1:8082',
37 | secure: false
38 | },
39 | '/zipkin': {
40 | target: process.env.ZIPKIN_URL || 'http://127.0.0.1:9411/api/v2/spans',
41 | pathRewrite: {
42 | '^/zipkin': ''
43 | },
44 | secure: false
45 | },
46 | },
47 | // CSS Sourcemaps off by default because relative paths are "buggy"
48 | // with this option, according to the CSS-Loader README
49 | // (https://github.com/webpack/css-loader#sourcemaps)
50 | // In our experience, they generally work as expected,
51 | // just be aware of this issue when enabling this option.
52 | cssSourceMap: false
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/frontend/config/prod.env.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | NODE_ENV: '"production"'
3 | }
4 |
--------------------------------------------------------------------------------
/frontend/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | frontend
7 |
8 |
9 |
10 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend",
3 | "version": "1.0.0",
4 | "description": "UI for sample distributed TODO app",
5 | "author": "elgris ",
6 | "private": true,
7 | "scripts": {
8 | "dev": "node build/dev-server.js",
9 | "start": "node build/dev-server.js",
10 | "build": "node build/build.js",
11 | "lint": "eslint --ext .js,.vue src"
12 | },
13 | "dependencies": {
14 | "bootstrap-vue": "^0.22.1",
15 | "jwt-decode": "^2.2.0",
16 | "vue": "^2.3.3",
17 | "vue-resource": "^1.3.4",
18 | "vue-router": "^2.6.0",
19 | "vuex": "^2.3.1",
20 | "zipkin": "^0.11.2",
21 | "zipkin-instrumentation-vue-resource": "^0.2.0",
22 | "zipkin-transport-http": "^0.11.2"
23 | },
24 | "devDependencies": {
25 | "node-sass": "^4.5.3",
26 | "sass-loader": "^6.0.6",
27 | "autoprefixer": "^7.1.2",
28 | "babel-core": "^6.22.1",
29 | "babel-eslint": "^7.1.1",
30 | "babel-loader": "^7.1.1",
31 | "babel-plugin-transform-runtime": "^6.22.0",
32 | "babel-preset-env": "^1.3.2",
33 | "babel-preset-stage-2": "^6.22.0",
34 | "babel-register": "^6.22.0",
35 | "chalk": "^2.0.1",
36 | "connect-history-api-fallback": "^1.3.0",
37 | "copy-webpack-plugin": "^4.0.1",
38 | "css-loader": "^0.28.5",
39 | "cssnano": "^3.10.0",
40 | "eslint": "^3.19.0",
41 | "eslint-config-standard": "^6.2.1",
42 | "eslint-friendly-formatter": "^3.0.0",
43 | "eslint-loader": "^1.7.1",
44 | "eslint-plugin-html": "^3.0.0",
45 | "eslint-plugin-promise": "^3.4.0",
46 | "eslint-plugin-standard": "^2.0.1",
47 | "eventsource-polyfill": "^0.9.6",
48 | "express": "^4.14.1",
49 | "extract-text-webpack-plugin": "^2.0.0",
50 | "file-loader": "^0.11.1",
51 | "friendly-errors-webpack-plugin": "^1.1.3",
52 | "html-webpack-plugin": "^2.28.0",
53 | "http-proxy-middleware": "^0.17.3",
54 | "opn": "^5.1.0",
55 | "optimize-css-assets-webpack-plugin": "^2.0.0",
56 | "ora": "^1.2.0",
57 | "rimraf": "^2.6.0",
58 | "semver": "^5.3.0",
59 | "shelljs": "^0.7.6",
60 | "url-loader": "^0.5.8",
61 | "vue-loader": "^12.1.0",
62 | "vue-style-loader": "^3.0.1",
63 | "vue-template-compiler": "^2.3.3",
64 | "webpack": "^2.6.1",
65 | "webpack-bundle-analyzer": "^2.2.1",
66 | "webpack-dev-middleware": "^1.10.0",
67 | "webpack-hot-middleware": "^2.18.0",
68 | "webpack-merge": "^4.1.0"
69 | },
70 | "engines": {
71 | "node": ">= 4.0.0",
72 | "npm": ">= 3.0.0"
73 | },
74 | "browserslist": [
75 | "> 1%",
76 | "last 2 versions",
77 | "not ie <= 8"
78 | ]
79 | }
80 |
--------------------------------------------------------------------------------
/frontend/src/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/frontend/src/assets/logo.png
--------------------------------------------------------------------------------
/frontend/src/auth.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import router from './router'
3 | import store from './store'
4 | import decode from 'jwt-decode'
5 |
6 | /**
7 | * @var{string} LOGIN_URL The endpoint for logging in. This endpoint should be proxied by Webpack dev server
8 | * and maybe nginx in production (cleaner calls and avoids CORS issues).
9 | */
10 | const LOGIN_URL = window.location.protocol + '//' + window.location.host + '/login'
11 | const ROLE_ADMIN = 'ADMIN'
12 |
13 | /**
14 | * Auth Plugin
15 | *
16 | * (see https://vuejs.org/v2/guide/plugins.html for more info on Vue.js plugins)
17 | *
18 | * Handles login and token authentication using OAuth2.
19 | */
20 | export default {
21 |
22 | /**
23 | * Install the Auth class.
24 | *
25 | * Creates a Vue-resource http interceptor to handle automatically adding auth headers
26 | * and refreshing tokens. Then attaches this object to the global Vue (as Vue.auth).
27 | *
28 | * @param {Object} Vue The global Vue.
29 | * @param {Object} options Any options we want to have in our plugin.
30 | * @return {void}
31 | */
32 | install (Vue, options) {
33 | Vue.http.interceptors.push((request, next) => {
34 | const token = store.state.auth.accessToken
35 | const hasAuthHeader = request.headers.has('Authorization')
36 |
37 | if (token && !hasAuthHeader) {
38 | this.setAuthHeader(request)
39 | }
40 |
41 | next()
42 | })
43 |
44 | Vue.prototype.$auth = Vue.auth = this
45 | },
46 |
47 | /**
48 | * Login
49 | *
50 | * @param {Object.} creds The username and password for logging in.
51 | * @param {string|null} redirect The name of the Route to redirect to.
52 | * @return {Promise}
53 | */
54 | login (creds, redirect) {
55 | const params = {
56 | username: creds.username,
57 | password: creds.password
58 | }
59 |
60 | return Vue.http.post(LOGIN_URL, params)
61 | .then((response) => {
62 | this._storeToken(response)
63 |
64 | if (redirect) {
65 | router.push({ name: redirect })
66 | }
67 |
68 | return response
69 | })
70 | .catch((errorResponse) => {
71 | return errorResponse
72 | })
73 | },
74 |
75 | /**
76 | * Logout
77 | *
78 | * Clear all data in our Vuex store (which resets logged-in status) and redirect back
79 | * to login form.
80 | *
81 | * @return {void}
82 | */
83 | logout () {
84 | store.commit('CLEAR_ALL_DATA')
85 | router.push({ name: 'login' })
86 | },
87 |
88 | /**
89 | * Set the Authorization header on a Vue-resource Request.
90 | *
91 | * @param {Request} request The Vue-Resource Request instance to set the header on.
92 | * @return {void}
93 | */
94 | setAuthHeader (request) {
95 | request.headers.set('Authorization', 'Bearer ' + store.state.auth.accessToken)
96 | },
97 |
98 | isAdmin () {
99 | const user = store.state.user
100 | return user.role === ROLE_ADMIN
101 | },
102 |
103 | isLoggedIn () {
104 | const auth = store.state.auth
105 | return auth.isLoggedIn
106 | },
107 |
108 | /**
109 | * Retry the original request.
110 | *
111 | * Let's retry the user's original target request that had recieved a invalid token response
112 | * (which we fixed with a token refresh).
113 | *
114 | * @param {Request} request The Vue-resource Request instance to use to repeat an http call.
115 | * @return {Promise}
116 | */
117 | _retry (request) {
118 | this.setAuthHeader(request)
119 |
120 | return Vue.http(request)
121 | .then((response) => {
122 | return response
123 | })
124 | .catch((response) => {
125 | return response
126 | })
127 | },
128 |
129 | /**
130 | * Store tokens
131 | *
132 | * Update the Vuex store with the access/refresh tokens received from the response from
133 | * the Oauth2 server.
134 | *
135 | * @private
136 | * @param {Response} response Vue-resource Response instance from an OAuth2 server.
137 | * that contains our tokens.
138 | * @return {void}
139 | */
140 | _storeToken (response) {
141 | const auth = store.state.auth
142 | auth.isLoggedIn = true
143 | auth.accessToken = response.body.accessToken
144 |
145 | var userData = decode(auth.accessToken)
146 |
147 | const user = store.state.user
148 | user.name = userData.name
149 | user.role = userData.role
150 |
151 | store.commit('UPDATE_AUTH', auth)
152 | store.commit('UPDATE_USER', user)
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/frontend/src/components/App.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
23 |
--------------------------------------------------------------------------------
/frontend/src/components/AppNav.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/frontend/src/components/Login.vue:
--------------------------------------------------------------------------------
1 |
2 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/frontend/src/components/TodoItem.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | {{ todo.content }}
5 |
6 |
7 |
8 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/frontend/src/components/Todos.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | TODOs
10 |
11 | ({{ total }})
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | {{ errorMessage }}
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/frontend/src/components/common/Spinner.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
{{ message }}
9 |
10 |
11 |
12 |
13 |
37 |
38 |
93 |
--------------------------------------------------------------------------------
/frontend/src/main.js:
--------------------------------------------------------------------------------
1 | // The Vue build version to load with the `import` command
2 | // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
3 | import Vue from 'vue'
4 | import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'
5 | import 'bootstrap/dist/css/bootstrap.css'
6 | import 'bootstrap-vue/dist/bootstrap-vue.css'
7 | Vue.use(BootstrapVue)
8 |
9 | import VueResource from 'vue-resource'
10 | Vue.use(VueResource)
11 |
12 | import App from '@/components/App'
13 | import router from './router'
14 | import store from './store'
15 |
16 | Vue.config.productionTip = false
17 |
18 | /* Auth plugin */
19 | import Auth from './auth'
20 | Vue.use(Auth)
21 |
22 | /* Auth plugin */
23 | import Zipkin from './zipkin'
24 | Vue.use(Zipkin)
25 |
26 | /* eslint-disable no-new */
27 | new Vue({
28 | el: '#app',
29 | router,
30 | store,
31 | template: '',
32 | components: { App }
33 | })
34 |
--------------------------------------------------------------------------------
/frontend/src/router/index.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 |
3 | import Auth from '@/auth'
4 | import Router from 'vue-router'
5 | Vue.use(Router)
6 |
7 | export default new Router({
8 | routes: [
9 | {
10 | path: '/login',
11 | name: 'login',
12 | component: require('@/components/Login.vue')
13 | },
14 | {
15 | path: '/',
16 | alias: '/todos',
17 | name: 'todos',
18 | component: require('@/components/Todos.vue'),
19 | beforeEnter: requireLoggedIn
20 | }
21 | ]
22 | })
23 |
24 | function requireLoggedIn (to, from, next) {
25 | if (!Auth.isLoggedIn()) {
26 | next({
27 | path: '/login',
28 | query: { redirect: to.fullPath }
29 | })
30 | } else {
31 | next()
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/frontend/src/store/index.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue'
2 | import Vuex from 'vuex'
3 | import { state } from './state'
4 | import * as mutations from './mutations'
5 | import plugins from './plugins'
6 |
7 | Vue.use(Vuex)
8 |
9 | const store = new Vuex.Store({
10 | state,
11 | mutations,
12 | plugins
13 | })
14 |
15 | export default store
16 |
--------------------------------------------------------------------------------
/frontend/src/store/mutations.js:
--------------------------------------------------------------------------------
1 | export const UPDATE_AUTH = (state, auth) => {
2 | state.auth = auth
3 | }
4 |
5 | export const UPDATE_USER = (state, user) => {
6 | state.user = user
7 | }
8 |
9 | export const CLEAR_ALL_DATA = (state) => {
10 | // Auth
11 | state.auth.isLoggedIn = false
12 | state.auth.accessToken = null
13 |
14 | // User
15 | state.user.name = ''
16 | state.user.role = null
17 | }
18 |
19 |
--------------------------------------------------------------------------------
/frontend/src/store/plugins.js:
--------------------------------------------------------------------------------
1 | import { STORAGE_KEY } from './state'
2 |
3 | const localStoragePlugin = store => {
4 | store.subscribe((mutation, state) => {
5 | const syncedData = { auth: state.auth, user: state.user }
6 |
7 | localStorage.setItem(STORAGE_KEY, JSON.stringify(syncedData))
8 |
9 | if (mutation.type === 'CLEAR_ALL_DATA') {
10 | localStorage.removeItem(STORAGE_KEY)
11 | }
12 | })
13 | }
14 |
15 | export default [localStoragePlugin]
16 |
--------------------------------------------------------------------------------
/frontend/src/store/state.js:
--------------------------------------------------------------------------------
1 | export const STORAGE_KEY = 'microservice-app-example-frontend'
2 |
3 | let syncedData = {
4 | auth: {
5 | isLoggedIn: false,
6 | accessToken: null,
7 | refreshToken: null
8 | },
9 | user: {
10 | name: null
11 | }
12 | }
13 |
14 | // Sync with local storage.
15 | if (localStorage.getItem(STORAGE_KEY)) {
16 | syncedData = JSON.parse(localStorage.getItem(STORAGE_KEY))
17 | }
18 |
19 | // Merge data and export it.
20 | export const state = Object.assign(syncedData)
21 |
--------------------------------------------------------------------------------
/frontend/src/zipkin.js:
--------------------------------------------------------------------------------
1 | import {
2 | Tracer,
3 | BatchRecorder,
4 | ExplicitContext,
5 | jsonEncoder
6 | } from 'zipkin'
7 | import {HttpLogger} from 'zipkin-transport-http'
8 | import {zipkinInterceptor} from 'zipkin-instrumentation-vue-resource'
9 | const ZIPKIN_URL = window.location.protocol + '//' + window.location.host + '/zipkin'
10 | /**
11 | * Tracing plugin that uses Zipkin. Initiates new traces with outgoing requests
12 | * and injects appropriate headers.
13 | */
14 | export default {
15 |
16 | /**
17 | * Install the Auth class.
18 | *
19 | * Creates a Vue-resource http interceptor to handle automatically adding auth headers
20 | * and refreshing tokens. Then attaches this object to the global Vue (as Vue.auth).
21 | *
22 | * @param {Object} Vue The global Vue.
23 | * @param {Object} options Any options we want to have in our plugin.
24 | * @return {void}
25 | */
26 | install (Vue, options) {
27 | const serviceName = 'frontend'
28 | const tracer = new Tracer({
29 | ctxImpl: new ExplicitContext(),
30 | recorder: new BatchRecorder({
31 | logger: new HttpLogger({
32 | endpoint: ZIPKIN_URL,
33 | jsonEncoder: jsonEncoder.JSON_V2
34 | })
35 | }),
36 | localServiceName: serviceName
37 | })
38 |
39 | const interceptor = zipkinInterceptor({tracer, serviceName})
40 | Vue.http.interceptors.push(interceptor)
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/frontend/static/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/frontend/static/.gitkeep
--------------------------------------------------------------------------------
/images/architecture.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/architecture.jpeg
--------------------------------------------------------------------------------
/images/cloud9-aws-settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-aws-settings.png
--------------------------------------------------------------------------------
/images/cloud9-disable-temp-creds.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-disable-temp-creds.png
--------------------------------------------------------------------------------
/images/cloud9-environments.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-environments.png
--------------------------------------------------------------------------------
/images/cloud9-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-logo.png
--------------------------------------------------------------------------------
/images/cloud9-preferences.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-preferences.png
--------------------------------------------------------------------------------
/images/cloud9-step-01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-step-01.png
--------------------------------------------------------------------------------
/images/cloud9-step-02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-step-02.png
--------------------------------------------------------------------------------
/images/cloud9-step-03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/images/cloud9-step-03.png
--------------------------------------------------------------------------------
/log-message-processor/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:3.6-alpine
2 |
3 | WORKDIR /usr/src/app
4 | RUN apk add --no-cache build-base
5 | COPY requirements.txt .
6 | RUN pip3 install -r requirements.txt
7 |
8 | COPY main.py .
9 |
10 | CMD ["python3","-u","main.py"]
11 |
12 |
--------------------------------------------------------------------------------
/log-message-processor/README.md:
--------------------------------------------------------------------------------
1 | # log-message-processor
2 | This service is written in Python3. This is a simple consumer that listens for
3 | new messages in Redis queue and prints message content to stdout. Message can be
4 | anything, there is no additional processing.
5 |
6 | ## Configuration
7 |
8 | The service scans environment for variables:
9 | - `REDIS_HOST` - host of Redis
10 | - `REDIS_PORT` - port of Redis
11 | - `REDIS_CHANNEL` - channel the processor is going to listen to
12 |
13 | ## Building and running
14 |
15 | ```
16 | pip3 install -r requirements.txt
17 | REDIS_HOST=127.0.0.1 REDIS_PORT=6379 REDIS_CHANNEL=log_channel python3 main.py
18 | ```
--------------------------------------------------------------------------------
/log-message-processor/main.py:
--------------------------------------------------------------------------------
1 | import time
2 | import redis
3 | import os
4 | import json
5 | import requests
6 | from py_zipkin.zipkin import zipkin_span, ZipkinAttrs, generate_random_64bit_string
7 | import time
8 | import random
9 |
10 | def log_message(message):
11 | time_delay = random.randrange(0, 2000)
12 | time.sleep(time_delay / 1000)
13 | print('message received after waiting for {}ms: {}'.format(time_delay, message))
14 |
15 | if __name__ == '__main__':
16 | redis_host = os.environ['REDIS_HOST']
17 | redis_port = int(os.environ['REDIS_PORT'])
18 | redis_channel = os.environ['REDIS_CHANNEL']
19 | zipkin_url = os.environ['ZIPKIN_URL'] if 'ZIPKIN_URL' in os.environ else ''
20 | def http_transport(encoded_span):
21 | requests.post(
22 | zipkin_url,
23 | data=encoded_span,
24 | headers={'Content-Type': 'application/x-thrift'},
25 | )
26 |
27 | pubsub = redis.Redis(host=redis_host, port=redis_port, db=0).pubsub()
28 | pubsub.subscribe([redis_channel])
29 | for item in pubsub.listen():
30 | try:
31 | message = json.loads(str(item['data'].decode("utf-8")))
32 | except Exception as e:
33 | log_message(e)
34 | continue
35 |
36 | if not zipkin_url or 'zipkinSpan' not in message:
37 | log_message(message)
38 | continue
39 |
40 | span_data = message['zipkinSpan']
41 | try:
42 | with zipkin_span(
43 | service_name='log-message-processor',
44 | zipkin_attrs=ZipkinAttrs(
45 | trace_id=span_data['_traceId']['value'],
46 | span_id=generate_random_64bit_string(),
47 | parent_span_id=span_data['_spanId'],
48 | is_sampled=span_data['_sampled']['value'],
49 | flags=None
50 | ),
51 | span_name='save_log',
52 | transport_handler=http_transport,
53 | sample_rate=100
54 | ):
55 | log_message(message)
56 | except Exception as e:
57 | print('did not send data to Zipkin: {}'.format(e))
58 | log_message(message)
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/log-message-processor/requirements.txt:
--------------------------------------------------------------------------------
1 | redis==2.10.6
2 | py_zipkin==0.11.0
3 | requests
--------------------------------------------------------------------------------
/run-your-own-dojo/README.md:
--------------------------------------------------------------------------------
1 | # Introduction
2 |
3 | This folder contains all the scripts to launch the infrastructure for you to run your own Dojo event. **Please note the following:**
4 |
5 | * This repository does its best at letting you know what resources will be launched. **Ultimately, it's your responsibility to pay any bills that running this challenge might incur.**
6 | * These scripts have been tested on macOS Monterey (version 12.1) using ZSH. Feel free to change the scripts and adapt them to Linux or Windows (create a folder for each OS or Linux Distro). Please submit a PR to collaborate to this repository.
7 | * These scripts are by no means as fully tested as the challenge is. There might be a lot of room for improvement. Again, PRs are welcome :)
8 | * This repository is not actively maintained. I will do my best to reply and look at issues and PRs
9 |
10 | # Resources launched by the script
11 |
12 | Once you run the scripts, the following AWS resources will be launched:
13 |
14 | * IAM Users
15 | * IAM Access Keys
16 | * IAM Policies
17 | * IAM Login Profile for each user
18 | * VPC
19 | * Internet Gateway
20 | * Subnets
21 | * Route Tables
22 | * Routes
23 | * KMS keys and aliases
24 | * EKS cluster
25 | * EKS Node Groups
26 | * ECR Repositories
27 | * Cloud9 Environments
28 |
29 | Make sure to use the [AWS Calculator](https://calculator.aws/#/) to know how much launching this infrastructure will cost you. Again, you are the sole responsible for paying your AWS bill, I'm sure you understand that :)
30 |
31 | # Prerequisites
32 |
33 | Before you run the `deploy-infra.sh` script, make sure to:
34 |
35 | * Install [Terraform v1.0+](https://www.terraform.io/downloads)
36 | * Install the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
37 | * Create a [Keybase](https://keybase.io/) user if you haven't got one yet and install the [Keybase app](https://keybase.io/docs/the_app/install_macos)
38 | * Install [jq](https://stedolan.github.io/jq/)
39 |
40 | When you run the `deploy-infra.sh` script, the script will ask you for the following:
41 |
42 | * `Enter minimum team number` - for this challenge, teams are numbered. If you will have 10 teams and would like to number them 1 to 10 (i.e., team1, team2, team3, team4, etc), enter `1` here.
43 | * `Enter maximum team number` - this is the number assigned to the last team. If you want to number teams 1 to 10, enter `10` here
44 | * `Enter the number of nodes for the cluster` - this is the number of EC2 instances to be used in your cluster. This does not take into account the [Control Plane](https://kubernetes.io/docs/concepts/overview/components/) (that's taken care by EKS). You are charged separately for the [Control Plane](https://aws.amazon.com/eks/pricing/)
45 | * `Enter the instance type for the nodes` - the EC2 instance type (t2.micro, t3.medium etc) for your Kubernetes nodes. **[Beware that each instance type can only handle a certain number of Pods](https://github.com/awslabs/amazon-eks-ami/blob/master/files/eni-max-pods.txt)**. If you run out of capacity, you will need to either increase the number of nodes or use a bigger and more powerful instance type
46 | * `Enter name of the AWS profile configured in your machine` - the name of the profile you used to configure your AWS CLI (i.e., when you ran `aws configure --profile `)
47 |
48 | Finally, you will notice that there's a file called `aws-auth-patch.yaml`. [This file basically gives permission to the IAM Users created by Terraform to access a single namespace in the cluster](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html). For example, if you specified you wanted 2 teams, Terraform will create two IAM Users (team1 and team2) and two Kubernetes namespaces (team1 and team2). The `aws-auth-patch.yaml` file basically tells Kubernetes you want the IAM User `team1` to only have access to the `team1` namespace and `team2` to only have access to the `team2` namespace. This is for security purposes so one team doesn't interfere with another team's namespace.
49 |
50 | Note that 10 teams have been hardcoded into this file. I still haven't had time to automate generating this file with a script, so if you will launch the infrastructure for more than 10 teams, feel free to add more entries to the `mapUsers` array (or write a script to automate generating this file, I'd love to see that!). For example:
51 |
52 | ```
53 | data:
54 | mapUsers: |
55 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team1
56 | username: team1
57 | groups:
58 | - team1-role
59 | (...)
60 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team9
61 | username: team9
62 | groups:
63 | - team9-role
64 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team10
65 | username: team10
66 | groups:
67 | - team10-role
68 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team11 <-- NEW ENTRY
69 | username: team11
70 | groups:
71 | - team11-role
72 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team12 <-- NEW ENTRY
73 | username: team12
74 | groups:
75 | - team12-role
76 | ```
77 |
78 | **PS: you don't need to replace `ACCOUNT_ID`. The script will do that automatically based on the AWS profile you specified.**
79 |
80 | **One more thing...** the deploy script is likely to run on Linux as is. However, you will probably need to change the `sed` command since the macOS implementation of `sed` is a bit different than the implementation for Linux. But apart from that, you shouldn't need to change the deploy script too much to run it on Linux.
81 |
82 | That's it! When you're ready, run `./deploy-infra.sh`.
83 |
84 | # Destroying the infrastructure
85 |
86 | Simply run `./destroy-infra.sh` and it should all be destroyed!
87 |
88 | # Support
89 |
90 | If you run into issues running the deploy script, open an issue or PR here on GitHub or DM me on [Twitter](https://twitter.com/DojoWithRenan) (@DojoWithRenan). I appreciate your interest in this repository!
91 |
--------------------------------------------------------------------------------
/run-your-own-dojo/macOS/aws-auth-patch.yaml:
--------------------------------------------------------------------------------
1 | data:
2 | mapUsers: |
3 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team1
4 | username: team1
5 | groups:
6 | - team1-role
7 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team2
8 | username: team2
9 | groups:
10 | - team2-role
11 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team3
12 | username: team3
13 | groups:
14 | - team3-role
15 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team4
16 | username: team4
17 | groups:
18 | - team4-role
19 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team5
20 | username: team5
21 | groups:
22 | - team5-role
23 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team6
24 | username: team6
25 | groups:
26 | - team6-role
27 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team7
28 | username: team7
29 | groups:
30 | - team7-role
31 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team8
32 | username: team8
33 | groups:
34 | - team8-role
35 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team9
36 | username: team9
37 | groups:
38 | - team9-role
39 | - userarn: arn:aws:iam::ACCOUNT_ID:user/team10
40 | username: team10
41 | groups:
42 | - team10-role
43 |
--------------------------------------------------------------------------------
/run-your-own-dojo/macOS/deploy-infra.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if ! command -v terraform &> /dev/null; then
4 | echo "terraform not installed. Install terraform v1.0+ before proceeding. Exiting..."
5 | exit
6 | fi
7 |
8 | if ! command -v aws &> /dev/null; then
9 | echo "aws not installed. Install the AWS CLI before proceeding. Exiting..."
10 | exit
11 | fi
12 |
13 | echo -n "Enter minimum team number (e.g. 1): " && read min
14 | echo -n "Enter maximum team number (e.g. 10): " && read max
15 | echo -n "Enter the number of nodes for the cluster: " && read cluster_size
16 | echo -n "Enter the instance type for the nodes (e.g. t2.micro): " && read instance_type
17 | echo -n "Enter name of the AWS profile configured in your machine (e.g. default): " && read aws_profile
18 | echo -n "Enter your keybase username in the form keybase:username (e.g. keybase:thedojoseries): " && read keybase_username
19 |
20 | export AWS_PROFILE=$aws_profile
21 |
22 | echo
23 | echo "Running as: $(aws sts get-caller-identity | jq -r .Arn). Make sure this is the right profile!"
24 | echo "Starting in 10 secs..."
25 | echo
26 |
27 | # This is to give you enough time to stop the script in case you're using the wrong profile
28 | sleep 10
29 |
30 | rm -rf .terraform
31 | terraform init
32 |
33 | # Deploys the cluster and Cloud9 environments
34 | # The command below will also configure your ~/.kube/config
35 | terraform apply \
36 | -var min_team_number=$min \
37 | -var max_team_number=$max \
38 | -var cluster_size=$cluster_size \
39 | -var instance_type=$instance_type \
40 | -var keybase_username=$keybase_username \
41 | -target module.eks_cluster
42 | echo
43 |
44 | # Waiting a few seconds before configuring the cluster
45 | echo "Sleeping for 15 secs..."
46 | sleep 15
47 |
48 | terraform apply \
49 | -var min_team_number=$min \
50 | -var max_team_number=$max \
51 | -var cluster_size=$cluster_size \
52 | -var instance_type=$instance_type \
53 | -target module.k8s_components \
54 | -auto-approve
55 |
56 | # Deploys Ingress Controller (i.e. Nginx)
57 | kubectl apply -f k8s/components/ingress-controller.yaml
58 |
59 | # Deploys Calico (for the Network Policies section)
60 | kubectl apply -f k8s/components/calico.yaml
61 | echo
62 |
63 | account_id=`aws sts get-caller-identity | jq -r .Account`
64 | sed -i '' "s/ACCOUNT_ID/$account_id/g" aws-auth-patch.yaml
65 |
66 | kubectl patch configmap aws-auth --patch-file aws-auth-patch.yaml -n kube-system
67 | echo
68 |
69 | # Increase Cloud9 Instance's volume. If you use the default volume size (10GB), you might run
70 | # out of disk space while building the Docker images. I'd suggest increasing to 20 or 30GB.
71 | # Change the size of the volume using the variable below.
72 | volume_size_gb=30
73 |
74 | for i in `seq $min $max`; do
75 | instance_id=`aws cloudformation describe-stack-resources --stack-name $(aws cloudformation describe-stacks | jq -r ".Stacks[] | select(.StackName | contains(\"aws-cloud9-team$i-\")) | .StackName") | jq -r '.StackResources[] | select(.ResourceType == "AWS::EC2::Instance") | .PhysicalResourceId'`
76 | volume_id=`aws ec2 describe-instances --instance-ids $instance_id | jq -r ".Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId"`
77 |
78 | aws ec2 modify-volume --size $volume_size_gb --volume-id $volume_id
79 | done
80 |
81 | # Wait for the volumes to be increased
82 | sleep_time=300
83 | echo "Sleeping for $sleep_time seconds before rebooting all Cloud9 instances..."
84 | sleep $sleep_time
85 |
86 | # Reboot all Cloud9 instances to make sure the filesystem recognizes the new volume size
87 | for i in `seq $min $max`; do
88 | instance_id=`aws cloudformation describe-stack-resources --stack-name $(aws cloudformation describe-stacks | jq -r ".Stacks[] | select(.StackName | contains(\"aws-cloud9-team$i-\")) | .StackName") | jq -r '.StackResources[] | select(.ResourceType == "AWS::EC2::Instance") | .PhysicalResourceId'`
89 | aws ec2 reboot-instances --instance-ids $instance_id
90 | done
91 |
92 | new_max=`expr $max - $min`
93 |
94 | # Print information about all the teams (i.e. AWS username, password, access key ID and secret access key)
95 | for i in `seq 0 $new_max`; do
96 | team=`expr $i + $min`
97 | echo "***** TEAM $team *****"
98 | echo Username: team$team
99 | echo Password: `terraform output -json passwords | jq -r ".[$i]" | base64 -D | keybase pgp decrypt | sed 's/;$//'`
100 | echo Access Key ID: `terraform output -json access_key_ids | jq -r ".[$i]"`
101 | echo Secret Access Key: `terraform output -json secret_access_keys | jq -r ".[$i]" | base64 -D | keybase pgp decrypt | sed 's/;$//'`
102 | echo "******************"
103 | echo
104 | done
105 |
106 | sed -i '' "s/$account_id/ACCOUNT_ID/g" aws-auth-patch.yaml
107 |
--------------------------------------------------------------------------------
/run-your-own-dojo/macOS/destroy-infra.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo -n "Enter name of the AWS profile configured in your machine (e.g. default): " && read aws_profile
4 | export AWS_PROFILE=$aws_profile
5 |
6 | echo Running as: `aws sts get-caller-identity | jq -r .Arn`
7 | echo "Starting in 10 secs..."
8 |
9 | # This is to give you enough time to stop the script in case you're using the wrong profile
10 | sleep 10
11 |
12 | echo "Destroying the Ingress Controller..."
13 | echo
14 | kubectl delete -f k8s/components/ingress-controller.yaml
15 |
16 | # The Network Load Balancer is created by Kubernetes and NOT Terraform.
17 | # If you destroy the infrastructure using Terraform before deleting the Load Balancer,
18 | # you will run into issues where the Load Balancer is using an ENI and Terraform is not able to delete
19 | # the subnets/VPC
20 | echo "Sleeping for a minute so the Network Load Balancer is destroyed before destroying the AWS resources..."
21 | echo
22 | sleep 60
23 |
24 | terraform apply -destroy -auto-approve -target module.eks_cluster
25 |
--------------------------------------------------------------------------------
/run-your-own-dojo/macOS/infra/main.tf:
--------------------------------------------------------------------------------
1 | data "aws_caller_identity" "current" {}
2 |
3 | #############
4 | # IAM Users #
5 | #############
6 |
7 | resource "aws_iam_user" "team_user" {
8 | count = var.max_team_number - var.min_team_number + 1
9 | name = "team${var.min_team_number + count.index}"
10 | path = "/"
11 |
12 | tags = {
13 | TeamName = "team${count.index + var.min_team_number}"
14 | Name = "team${var.min_team_number + count.index}"
15 | Event = "Kubernetes"
16 | }
17 | }
18 |
19 | resource "aws_iam_access_key" "access_keys" {
20 | count = var.max_team_number - var.min_team_number + 1
21 | user = aws_iam_user.team_user[count.index].name
22 | pgp_key = "keybase:thedojoseries"
23 | }
24 |
25 | resource "aws_iam_policy" "user_policy" {
26 | count = var.max_team_number - var.min_team_number + 1
27 | name = "k8s-ctf-user-policy-team${count.index + var.min_team_number}"
28 | description = "The Policy to be assigned to the Kubernetes users"
29 | policy = <",
10 | "license": "MIT",
11 | "dependencies": {
12 | "body-parser": "^1.18.2",
13 | "express": "^4.15.4",
14 | "express-jwt": "^5.3.0",
15 | "memory-cache": "^0.2.0",
16 | "redis": "^2.8.0",
17 | "zipkin": "^0.11.2",
18 | "zipkin-context-cls": "^0.11.0",
19 | "zipkin-instrumentation-express": "^0.11.2",
20 | "zipkin-transport-http": "^0.11.2"
21 | },
22 | "devDependencies": {
23 | "nodemon": "^1.11.0"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/todos-api/routes.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | const TodoController = require('./todoController');
3 | module.exports = function (app, {tracer, redisClient, logChannel}) {
4 | const todoController = new TodoController({tracer, redisClient, logChannel});
5 | app.route('/todos')
6 | .get(function(req,resp) {return todoController.list(req,resp)})
7 | .post(function(req,resp) {return todoController.create(req,resp)});
8 |
9 | app.route('/todos/:taskId')
10 | .delete(function(req,resp) {return todoController.delete(req,resp)});
11 | };
--------------------------------------------------------------------------------
/todos-api/server.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | const express = require('express')
3 | const bodyParser = require("body-parser")
4 | const jwt = require('express-jwt')
5 |
6 | const ZIPKIN_URL = process.env.ZIPKIN_URL || 'http://127.0.0.1:9411/api/v2/spans';
7 | const {Tracer,
8 | BatchRecorder,
9 | jsonEncoder: {JSON_V2}} = require('zipkin');
10 | const CLSContext = require('zipkin-context-cls');
11 | const {HttpLogger} = require('zipkin-transport-http');
12 | const zipkinMiddleware = require('zipkin-instrumentation-express').expressMiddleware;
13 |
14 | const logChannel = process.env.REDIS_CHANNEL || 'log_channel';
15 | const redisClient = require("redis").createClient({
16 | host: process.env.REDIS_HOST || 'localhost',
17 | port: process.env.REDIS_PORT || 6379,
18 | retry_strategy: function (options) {
19 | if (options.error && options.error.code === 'ECONNREFUSED') {
20 | return new Error('The server refused the connection');
21 | }
22 | if (options.total_retry_time > 1000 * 60 * 60) {
23 | return new Error('Retry time exhausted');
24 | }
25 | if (options.attempt > 10) {
26 | console.log('reattemtping to connect to redis, attempt #' + options.attempt)
27 | return undefined;
28 | }
29 | return Math.min(options.attempt * 100, 2000);
30 | }
31 | });
32 | const port = process.env.TODO_API_PORT || 8082
33 | const jwtSecret = process.env.JWT_SECRET || "foo"
34 |
35 | const app = express()
36 |
37 | // tracing
38 | const ctxImpl = new CLSContext('zipkin');
39 | const recorder = new BatchRecorder({
40 | logger: new HttpLogger({
41 | endpoint: ZIPKIN_URL,
42 | jsonEncoder: JSON_V2
43 | })
44 | });
45 | const localServiceName = 'todos-api';
46 | const tracer = new Tracer({ctxImpl, recorder, localServiceName});
47 |
48 |
49 | app.use(jwt({ secret: jwtSecret }))
50 | app.use(zipkinMiddleware({tracer}));
51 | app.use(function (err, req, res, next) {
52 | if (err.name === 'UnauthorizedError') {
53 | res.status(401).send({ message: 'invalid token' })
54 | }
55 | })
56 | app.use(bodyParser.urlencoded({ extended: false }))
57 | app.use(bodyParser.json())
58 |
59 | const routes = require('./routes')
60 | routes(app, {tracer, redisClient, logChannel})
61 |
62 | app.listen(port, function () {
63 | console.log('todo list RESTful API server started on: ' + port)
64 | })
65 |
--------------------------------------------------------------------------------
/todos-api/todoController.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | const cache = require('memory-cache');
3 | const {Annotation,
4 | jsonEncoder: {JSON_V2}} = require('zipkin');
5 |
6 | const OPERATION_CREATE = 'CREATE',
7 | OPERATION_DELETE = 'DELETE';
8 |
9 | class TodoController {
10 | constructor({tracer, redisClient, logChannel}) {
11 | this._tracer = tracer;
12 | this._redisClient = redisClient;
13 | this._logChannel = logChannel;
14 | }
15 |
16 | // TODO: these methods are not concurrent-safe
17 | list (req, res) {
18 | const data = this._getTodoData(req.user.username)
19 |
20 | res.json(data.items)
21 | }
22 |
23 | create (req, res) {
24 | // TODO: must be transactional and protected for concurrent access, but
25 | // the purpose of the whole example app it's enough
26 | const data = this._getTodoData(req.user.username)
27 | const todo = {
28 | content: req.body.content,
29 | id: data.lastInsertedID
30 | }
31 | data.items[data.lastInsertedID] = todo
32 |
33 | data.lastInsertedID++
34 | this._setTodoData(req.user.username, data)
35 |
36 | this._logOperation(OPERATION_CREATE, req.user.username, todo.id)
37 |
38 | res.json(todo)
39 | }
40 |
41 | delete (req, res) {
42 | const data = this._getTodoData(req.user.username)
43 | const id = req.params.taskId
44 | delete data.items[id]
45 | this._setTodoData(req.user.username, data)
46 |
47 | this._logOperation(OPERATION_DELETE, req.user.username, id)
48 |
49 | res.status(204)
50 | res.send()
51 | }
52 |
53 | _logOperation (opName, username, todoId) {
54 | this._tracer.scoped(() => {
55 | const traceId = this._tracer.id;
56 | this._redisClient.publish(this._logChannel, JSON.stringify({
57 | zipkinSpan: traceId,
58 | opName: opName,
59 | username: username,
60 | todoId: todoId,
61 | }))
62 | })
63 | }
64 |
65 | _getTodoData (userID) {
66 | var data = cache.get(userID)
67 | if (data == null) {
68 | data = {
69 | items: {
70 | '1': {
71 | id: 1,
72 | content: "Create new todo",
73 | },
74 | '2': {
75 | id: 2,
76 | content: "Update me",
77 | },
78 | '3': {
79 | id: 3,
80 | content: "Delete example ones",
81 | }
82 | },
83 | lastInsertedID: 3
84 | }
85 |
86 | this._setTodoData(userID, data)
87 | }
88 | return data
89 | }
90 |
91 | _setTodoData (userID, data) {
92 | cache.put(userID, data)
93 | }
94 | }
95 |
96 | module.exports = TodoController
--------------------------------------------------------------------------------
/users-api/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 |
4 | ### STS ###
5 | .apt_generated
6 | .classpath
7 | .factorypath
8 | .project
9 | .settings
10 | .springBeans
11 |
12 | ### IntelliJ IDEA ###
13 | .idea
14 | *.iws
15 | *.iml
16 | *.ipr
17 |
18 | ### NetBeans ###
19 | nbproject/private/
20 | build/
21 | nbbuild/
22 | dist/
23 | nbdist/
24 | .nb-gradle/
--------------------------------------------------------------------------------
/users-api/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thedojoseries/kubernetes/fab0fa3802684ec252723f2d53eb2acd4dbd864a/users-api/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/users-api/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip
2 |
--------------------------------------------------------------------------------
/users-api/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:8-alpine
2 |
3 | EXPOSE 8083
4 | WORKDIR /usr/src/app
5 |
6 |
7 | COPY pom.xml mvnw ./
8 | COPY .mvn/ ./.mvn
9 | RUN ./mvnw dependency:resolve
10 |
11 | COPY . .
12 | RUN ./mvnw install
13 |
14 | CMD ["java", "-jar", "./target/users-api-0.0.1-SNAPSHOT.jar"]
15 |
--------------------------------------------------------------------------------
/users-api/README.md:
--------------------------------------------------------------------------------
1 | # users-api
2 | This service is written in Java with SpringBoot. It provides simple API to retrieve user data.
3 |
4 | - `GET /users` - list all users
5 | - `GET /users/:username` - get a user by name
6 |
7 | ## Configuration
8 |
9 | The service scans environment for variables:
10 | - `JWT_SECRET` - secret value for JWT token processing.
11 | - `SERVER_PORT` - the port the service takes.
12 |
13 | ## Building and running
14 |
15 | ```
16 | ./mvnw clean install
17 | JWT_SECRET=foo SERVER_PORT=8083 java -jar target/users-api-0.0.1-SNAPSHOT.jar
18 | ```
--------------------------------------------------------------------------------
/users-api/mvnw:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # ----------------------------------------------------------------------------
3 | # Licensed to the Apache Software Foundation (ASF) under one
4 | # or more contributor license agreements. See the NOTICE file
5 | # distributed with this work for additional information
6 | # regarding copyright ownership. The ASF licenses this file
7 | # to you under the Apache License, Version 2.0 (the
8 | # "License"); you may not use this file except in compliance
9 | # with the License. You may obtain a copy of the License at
10 | #
11 | # http://www.apache.org/licenses/LICENSE-2.0
12 | #
13 | # Unless required by applicable law or agreed to in writing,
14 | # software distributed under the License is distributed on an
15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 | # KIND, either express or implied. See the License for the
17 | # specific language governing permissions and limitations
18 | # under the License.
19 | # ----------------------------------------------------------------------------
20 |
21 | # ----------------------------------------------------------------------------
22 | # Maven2 Start Up Batch script
23 | #
24 | # Required ENV vars:
25 | # ------------------
26 | # JAVA_HOME - location of a JDK home dir
27 | #
28 | # Optional ENV vars
29 | # -----------------
30 | # M2_HOME - location of maven2's installed home dir
31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven
32 | # e.g. to debug Maven itself, use
33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files
35 | # ----------------------------------------------------------------------------
36 |
37 | if [ -z "$MAVEN_SKIP_RC" ] ; then
38 |
39 | if [ -f /etc/mavenrc ] ; then
40 | . /etc/mavenrc
41 | fi
42 |
43 | if [ -f "$HOME/.mavenrc" ] ; then
44 | . "$HOME/.mavenrc"
45 | fi
46 |
47 | fi
48 |
49 | # OS specific support. $var _must_ be set to either true or false.
50 | cygwin=false;
51 | darwin=false;
52 | mingw=false
53 | case "`uname`" in
54 | CYGWIN*) cygwin=true ;;
55 | MINGW*) mingw=true;;
56 | Darwin*) darwin=true
57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
59 | if [ -z "$JAVA_HOME" ]; then
60 | if [ -x "/usr/libexec/java_home" ]; then
61 | export JAVA_HOME="`/usr/libexec/java_home`"
62 | else
63 | export JAVA_HOME="/Library/Java/Home"
64 | fi
65 | fi
66 | ;;
67 | esac
68 |
69 | if [ -z "$JAVA_HOME" ] ; then
70 | if [ -r /etc/gentoo-release ] ; then
71 | JAVA_HOME=`java-config --jre-home`
72 | fi
73 | fi
74 |
75 | if [ -z "$M2_HOME" ] ; then
76 | ## resolve links - $0 may be a link to maven's home
77 | PRG="$0"
78 |
79 | # need this for relative symlinks
80 | while [ -h "$PRG" ] ; do
81 | ls=`ls -ld "$PRG"`
82 | link=`expr "$ls" : '.*-> \(.*\)$'`
83 | if expr "$link" : '/.*' > /dev/null; then
84 | PRG="$link"
85 | else
86 | PRG="`dirname "$PRG"`/$link"
87 | fi
88 | done
89 |
90 | saveddir=`pwd`
91 |
92 | M2_HOME=`dirname "$PRG"`/..
93 |
94 | # make it fully qualified
95 | M2_HOME=`cd "$M2_HOME" && pwd`
96 |
97 | cd "$saveddir"
98 | # echo Using m2 at $M2_HOME
99 | fi
100 |
101 | # For Cygwin, ensure paths are in UNIX format before anything is touched
102 | if $cygwin ; then
103 | [ -n "$M2_HOME" ] &&
104 | M2_HOME=`cygpath --unix "$M2_HOME"`
105 | [ -n "$JAVA_HOME" ] &&
106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
107 | [ -n "$CLASSPATH" ] &&
108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
109 | fi
110 |
111 | # For Migwn, ensure paths are in UNIX format before anything is touched
112 | if $mingw ; then
113 | [ -n "$M2_HOME" ] &&
114 | M2_HOME="`(cd "$M2_HOME"; pwd)`"
115 | [ -n "$JAVA_HOME" ] &&
116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
117 | # TODO classpath?
118 | fi
119 |
120 | if [ -z "$JAVA_HOME" ]; then
121 | javaExecutable="`which javac`"
122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
123 | # readlink(1) is not available as standard on Solaris 10.
124 | readLink=`which readlink`
125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
126 | if $darwin ; then
127 | javaHome="`dirname \"$javaExecutable\"`"
128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
129 | else
130 | javaExecutable="`readlink -f \"$javaExecutable\"`"
131 | fi
132 | javaHome="`dirname \"$javaExecutable\"`"
133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'`
134 | JAVA_HOME="$javaHome"
135 | export JAVA_HOME
136 | fi
137 | fi
138 | fi
139 |
140 | if [ -z "$JAVACMD" ] ; then
141 | if [ -n "$JAVA_HOME" ] ; then
142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
143 | # IBM's JDK on AIX uses strange locations for the executables
144 | JAVACMD="$JAVA_HOME/jre/sh/java"
145 | else
146 | JAVACMD="$JAVA_HOME/bin/java"
147 | fi
148 | else
149 | JAVACMD="`which java`"
150 | fi
151 | fi
152 |
153 | if [ ! -x "$JAVACMD" ] ; then
154 | echo "Error: JAVA_HOME is not defined correctly." >&2
155 | echo " We cannot execute $JAVACMD" >&2
156 | exit 1
157 | fi
158 |
159 | if [ -z "$JAVA_HOME" ] ; then
160 | echo "Warning: JAVA_HOME environment variable is not set."
161 | fi
162 |
163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
164 |
165 | # traverses directory structure from process work directory to filesystem root
166 | # first directory with .mvn subdirectory is considered project base directory
167 | find_maven_basedir() {
168 |
169 | if [ -z "$1" ]
170 | then
171 | echo "Path not specified to find_maven_basedir"
172 | return 1
173 | fi
174 |
175 | basedir="$1"
176 | wdir="$1"
177 | while [ "$wdir" != '/' ] ; do
178 | if [ -d "$wdir"/.mvn ] ; then
179 | basedir=$wdir
180 | break
181 | fi
182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc)
183 | if [ -d "${wdir}" ]; then
184 | wdir=`cd "$wdir/.."; pwd`
185 | fi
186 | # end of workaround
187 | done
188 | echo "${basedir}"
189 | }
190 |
191 | # concatenates all lines of a file
192 | concat_lines() {
193 | if [ -f "$1" ]; then
194 | echo "$(tr -s '\n' ' ' < "$1")"
195 | fi
196 | }
197 |
198 | BASE_DIR=`find_maven_basedir "$(pwd)"`
199 | if [ -z "$BASE_DIR" ]; then
200 | exit 1;
201 | fi
202 |
203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
204 | echo $MAVEN_PROJECTBASEDIR
205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
206 |
207 | # For Cygwin, switch paths to Windows format before running java
208 | if $cygwin; then
209 | [ -n "$M2_HOME" ] &&
210 | M2_HOME=`cygpath --path --windows "$M2_HOME"`
211 | [ -n "$JAVA_HOME" ] &&
212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
213 | [ -n "$CLASSPATH" ] &&
214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
215 | [ -n "$MAVEN_PROJECTBASEDIR" ] &&
216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
217 | fi
218 |
219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
220 |
221 | exec "$JAVACMD" \
222 | $MAVEN_OPTS \
223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
226 |
--------------------------------------------------------------------------------
/users-api/mvnw.cmd:
--------------------------------------------------------------------------------
1 | @REM ----------------------------------------------------------------------------
2 | @REM Licensed to the Apache Software Foundation (ASF) under one
3 | @REM or more contributor license agreements. See the NOTICE file
4 | @REM distributed with this work for additional information
5 | @REM regarding copyright ownership. The ASF licenses this file
6 | @REM to you under the Apache License, Version 2.0 (the
7 | @REM "License"); you may not use this file except in compliance
8 | @REM with the License. You may obtain a copy of the License at
9 | @REM
10 | @REM http://www.apache.org/licenses/LICENSE-2.0
11 | @REM
12 | @REM Unless required by applicable law or agreed to in writing,
13 | @REM software distributed under the License is distributed on an
14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | @REM KIND, either express or implied. See the License for the
16 | @REM specific language governing permissions and limitations
17 | @REM under the License.
18 | @REM ----------------------------------------------------------------------------
19 |
20 | @REM ----------------------------------------------------------------------------
21 | @REM Maven2 Start Up Batch script
22 | @REM
23 | @REM Required ENV vars:
24 | @REM JAVA_HOME - location of a JDK home dir
25 | @REM
26 | @REM Optional ENV vars
27 | @REM M2_HOME - location of maven2's installed home dir
28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
31 | @REM e.g. to debug Maven itself, use
32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
34 | @REM ----------------------------------------------------------------------------
35 |
36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
37 | @echo off
38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
40 |
41 | @REM set %HOME% to equivalent of $HOME
42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
43 |
44 | @REM Execute a user defined script before this one
45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending
47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
49 | :skipRcPre
50 |
51 | @setlocal
52 |
53 | set ERROR_CODE=0
54 |
55 | @REM To isolate internal variables from possible post scripts, we use another setlocal
56 | @setlocal
57 |
58 | @REM ==== START VALIDATION ====
59 | if not "%JAVA_HOME%" == "" goto OkJHome
60 |
61 | echo.
62 | echo Error: JAVA_HOME not found in your environment. >&2
63 | echo Please set the JAVA_HOME variable in your environment to match the >&2
64 | echo location of your Java installation. >&2
65 | echo.
66 | goto error
67 |
68 | :OkJHome
69 | if exist "%JAVA_HOME%\bin\java.exe" goto init
70 |
71 | echo.
72 | echo Error: JAVA_HOME is set to an invalid directory. >&2
73 | echo JAVA_HOME = "%JAVA_HOME%" >&2
74 | echo Please set the JAVA_HOME variable in your environment to match the >&2
75 | echo location of your Java installation. >&2
76 | echo.
77 | goto error
78 |
79 | @REM ==== END VALIDATION ====
80 |
81 | :init
82 |
83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
84 | @REM Fallback to current working directory if not found.
85 |
86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
88 |
89 | set EXEC_DIR=%CD%
90 | set WDIR=%EXEC_DIR%
91 | :findBaseDir
92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound
93 | cd ..
94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound
95 | set WDIR=%CD%
96 | goto findBaseDir
97 |
98 | :baseDirFound
99 | set MAVEN_PROJECTBASEDIR=%WDIR%
100 | cd "%EXEC_DIR%"
101 | goto endDetectBaseDir
102 |
103 | :baseDirNotFound
104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
105 | cd "%EXEC_DIR%"
106 |
107 | :endDetectBaseDir
108 |
109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
110 |
111 | @setlocal EnableExtensions EnableDelayedExpansion
112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
114 |
115 | :endReadAdditionalConfig
116 |
117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
118 |
119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
121 |
122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
123 | if ERRORLEVEL 1 goto error
124 | goto end
125 |
126 | :error
127 | set ERROR_CODE=1
128 |
129 | :end
130 | @endlocal & set ERROR_CODE=%ERROR_CODE%
131 |
132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending
134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
136 | :skipRcPost
137 |
138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause
140 |
141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
142 |
143 | exit /B %ERROR_CODE%
144 |
--------------------------------------------------------------------------------
/users-api/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | com.elgris
7 | users-api
8 | 0.0.1-SNAPSHOT
9 | jar
10 |
11 | users-api
12 | Demo project for Spring Boot
13 |
14 |
15 | org.springframework.boot
16 | spring-boot-starter-parent
17 | 1.5.6.RELEASE
18 |
19 |
20 |
21 |
22 | UTF-8
23 | UTF-8
24 | 1.8
25 |
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-security
35 |
36 |
37 |
38 | io.jsonwebtoken
39 | jjwt
40 | 0.7.0
41 |
42 |
43 |
44 | org.springframework.boot
45 | spring-boot-starter-data-jpa
46 |
47 |
48 |
49 | com.h2database
50 | h2
51 |
52 |
53 |
54 | org.springframework.cloud
55 | spring-cloud-starter-zipkin
56 | 1.3.1.RELEASE
57 |
58 |
59 |
60 | org.springframework.boot
61 | spring-boot-starter-test
62 | test
63 |
64 |
65 |
66 |
67 |
68 |
69 | org.springframework.boot
70 | spring-boot-maven-plugin
71 |
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/UsersApiApplication.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi;
2 |
3 | import com.elgris.usersapi.security.JwtAuthenticationFilter;
4 | import org.springframework.boot.SpringApplication;
5 | import org.springframework.boot.autoconfigure.SpringBootApplication;
6 | import org.springframework.boot.web.servlet.FilterRegistrationBean;
7 | import org.springframework.context.annotation.Bean;
8 |
9 | @SpringBootApplication
10 | public class UsersApiApplication {
11 |
12 | public static void main(String[] args) {
13 | SpringApplication.run(UsersApiApplication.class, args);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/api/UsersController.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.api;
2 |
3 | import com.elgris.usersapi.models.User;
4 | import com.elgris.usersapi.repository.UserRepository;
5 | import io.jsonwebtoken.Claims;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.security.access.AccessDeniedException;
8 | import org.springframework.web.bind.annotation.*;
9 |
10 | import javax.servlet.http.HttpServletRequest;
11 | import java.util.LinkedList;
12 | import java.util.List;
13 |
14 | @RestController()
15 | @RequestMapping("/users")
16 | public class UsersController {
17 |
18 | @Autowired
19 | private UserRepository userRepository;
20 |
21 |
22 | @RequestMapping(value = "/", method = RequestMethod.GET)
23 | public List getUsers() {
24 | List response = new LinkedList<>();
25 | userRepository.findAll().forEach(response::add);
26 |
27 | return response;
28 | }
29 |
30 | @RequestMapping(value = "/{username}", method = RequestMethod.GET)
31 | public User getUser(HttpServletRequest request, @PathVariable("username") String username) {
32 |
33 | Object requestAttribute = request.getAttribute("claims");
34 | if((requestAttribute == null) || !(requestAttribute instanceof Claims)){
35 | throw new RuntimeException("Did not receive required data from JWT token");
36 | }
37 |
38 | Claims claims = (Claims) requestAttribute;
39 |
40 | if (!username.equalsIgnoreCase((String)claims.get("username"))) {
41 | throw new AccessDeniedException("No access for requested entity");
42 | }
43 |
44 | return userRepository.findOneByUsername(username);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/configuration/SecurityConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.configuration;
2 |
3 | import com.elgris.usersapi.security.JwtAuthenticationFilter;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.context.annotation.Configuration;
6 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
11 |
12 | @EnableWebSecurity
13 | @EnableGlobalMethodSecurity(securedEnabled = true)
14 | class HttpSecurityConfiguration {
15 |
16 | @Configuration
17 | public static class ApiConfigurerAdatper extends WebSecurityConfigurerAdapter {
18 |
19 | @Autowired
20 | private JwtAuthenticationFilter jwtAuthenticationFilter;
21 |
22 | @Override
23 | protected void configure(HttpSecurity http) throws Exception {
24 | http.antMatcher("/**")
25 | .addFilterAfter(jwtAuthenticationFilter, BasicAuthenticationFilter.class);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/models/User.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.models;
2 |
3 | import javax.persistence.*;
4 |
5 | @Entity
6 | @Table(name = "users")
7 | public class User {
8 |
9 | @Id
10 | @Column
11 | private String username;
12 | @Column
13 | private String firstname;
14 | @Column
15 | private String lastname;
16 | @Column
17 | private UserRole role;
18 |
19 | public String getUsername() {
20 | return username;
21 | }
22 |
23 | public void setUsername(String username) {
24 | this.username = username;
25 | }
26 |
27 | public String getFirstname() {
28 | return firstname;
29 | }
30 |
31 | public void setFirstname(String firstname) {
32 | this.firstname = firstname;
33 | }
34 |
35 | public String getLastname() {
36 | return lastname;
37 | }
38 |
39 | public void setLastname(String lastname) {
40 | this.lastname = lastname;
41 | }
42 |
43 | public UserRole getRole() {
44 | return role;
45 | }
46 |
47 | public void setRole(UserRole role) {
48 | this.role = role;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/models/UserRole.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.models;
2 |
3 | public enum UserRole {
4 | USER("user"),
5 | ADMIN("admin");
6 |
7 | private String description;
8 | UserRole(final String description) {
9 | this.description = description;
10 | }
11 |
12 |
13 | @Override
14 | public String toString() {
15 | return this.description;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/repository/UserRepository.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.repository;
2 |
3 | import com.elgris.usersapi.models.User;
4 | import org.springframework.data.repository.CrudRepository;
5 |
6 | import java.util.List;
7 |
8 | public interface UserRepository extends CrudRepository {
9 | User findOneByUsername(String username);
10 | User findByUsername(String username);
11 | User getByUsername(String username);
12 | }
13 |
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/security/AccessUserFilter.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.security;
2 |
3 | import io.jsonwebtoken.Claims;
4 | import io.jsonwebtoken.Jwts;
5 | import io.jsonwebtoken.SignatureException;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.stereotype.Component;
8 | import org.springframework.web.filter.GenericFilterBean;
9 |
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.ServletException;
12 | import javax.servlet.ServletRequest;
13 | import javax.servlet.ServletResponse;
14 | import javax.servlet.http.HttpServletRequest;
15 | import javax.servlet.http.HttpServletResponse;
16 | import java.io.IOException;
17 |
18 | public class AccessUserFilter extends GenericFilterBean {
19 |
20 | public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
21 | throws IOException, ServletException {
22 | req.getAttribute("claims");
23 | }
24 | }
--------------------------------------------------------------------------------
/users-api/src/main/java/com/elgris/usersapi/security/JwtAuthenticationFilter.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi.security;
2 |
3 | import io.jsonwebtoken.Claims;
4 | import io.jsonwebtoken.Jwts;
5 | import io.jsonwebtoken.SignatureException;
6 | import org.springframework.beans.factory.annotation.Value;
7 | import org.springframework.stereotype.Component;
8 | import org.springframework.web.filter.GenericFilterBean;
9 |
10 | import javax.servlet.FilterChain;
11 | import javax.servlet.ServletException;
12 | import javax.servlet.ServletRequest;
13 | import javax.servlet.ServletResponse;
14 | import javax.servlet.http.HttpServletRequest;
15 | import javax.servlet.http.HttpServletResponse;
16 | import java.io.IOException;
17 |
18 | @Component
19 | public class JwtAuthenticationFilter extends GenericFilterBean {
20 |
21 | @Value("${jwt.secret}")
22 | private String jwtSecret;
23 |
24 | public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
25 | throws IOException, ServletException {
26 |
27 | final HttpServletRequest request = (HttpServletRequest) req;
28 | final HttpServletResponse response = (HttpServletResponse) res;
29 | final String authHeader = request.getHeader("authorization");
30 |
31 | if ("OPTIONS".equals(request.getMethod())) {
32 | response.setStatus(HttpServletResponse.SC_OK);
33 |
34 | chain.doFilter(req, res);
35 | } else {
36 |
37 | if (authHeader == null || !authHeader.startsWith("Bearer ")) {
38 | throw new ServletException("Missing or invalid Authorization header");
39 | }
40 |
41 | final String token = authHeader.substring(7);
42 |
43 | try {
44 | final Claims claims = Jwts.parser()
45 | .setSigningKey(jwtSecret.getBytes())
46 | .parseClaimsJws(token)
47 | .getBody();
48 | request.setAttribute("claims", claims);
49 | } catch (final SignatureException e) {
50 | throw new ServletException("Invalid token");
51 | }
52 |
53 | chain.doFilter(req, res);
54 | }
55 | }
56 | }
--------------------------------------------------------------------------------
/users-api/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | jwt.secret=myfancysecret
2 | server.port=8083
3 |
4 | spring.application.name=users-api
5 | spring.zipkin.baseUrl=http://127.0.0.1:9411/
6 | spring.sleuth.sampler.percentage=100.0
--------------------------------------------------------------------------------
/users-api/src/main/resources/data.sql:
--------------------------------------------------------------------------------
1 | INSERT INTO users (username, firstname, lastname, role) VALUES
2 | ('admin', 'Foo', 'Bar', 1),
3 | ('johnd', 'John', 'Doe', 0),
4 | ('janed', 'Jane', 'Doe', 0);
--------------------------------------------------------------------------------
/users-api/src/test/java/com/elgris/usersapi/UsersApiApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.elgris.usersapi;
2 |
3 | import org.junit.Test;
4 | import org.junit.runner.RunWith;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.junit4.SpringRunner;
7 |
8 | @RunWith(SpringRunner.class)
9 | @SpringBootTest
10 | public class UsersApiApplicationTests {
11 |
12 | @Test
13 | public void contextLoads() {
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------