diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 7c22873..bb20778 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -11,33 +11,33 @@ jobs: runs-on: ubuntu-latest steps: - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: - go-version: 1.17 - - uses: actions/checkout@v3 + go-version: 1.22 + - uses: actions/checkout@v4 - name: golangci-lint - uses: golangci/golangci-lint-action@v2 + uses: golangci/golangci-lint-action@v4 with: skip-go-installation: true - args: --version - version: v1.44.2 + args: --version + version: v1.54 tests: name: tests needs: lint runs-on: ubuntu-latest steps: - - name: Set up Go 1.17 - uses: actions/setup-go@v2 - with: - go-version: '1.17' - id: go - - uses: actions/checkout@v2 - - uses: actions/cache@v1 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }} - restore-keys: | - ${{ runner.os }}-go - - name: Buffalo Tests - run: | - go test --cover ./... -v \ No newline at end of file + - name: Set up Go 1.22 + uses: actions/setup-go@v5 + with: + go-version: "1.22" + id: go + - uses: actions/checkout@v4 + - uses: actions/cache@v4 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }} + restore-keys: | + ${{ runner.os }}-go + - name: test + run: | + go test --cover ./... -v diff --git a/.gitignore b/.gitignore index 692c2fc..acb7558 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .DS_Store -bin \ No newline at end of file +bin +tmp diff --git a/README.md b/README.md index 269069f..b60655e 100644 --- a/README.md +++ b/README.md @@ -1,256 +1,64 @@ -![tests workflow](https://github.com/wawandco/maildoor/actions/workflows/test.yml/badge.svg) ![report card](https://goreportcard.com/badge/github.com/wawandco/maildoor) - # Maildoor -![maildoor banner](./showcase-cover.png) - -Maildoor is an email based authentication library for Go (lang), powered by Go `embed` package, JWT's and TailwindCSS. Maildoor provides simple and beautiful user interface that is easy to use and customize with your logo. - -
- - -
- -But the UI is not all, Maildoor ships as a Go handler that contains the needed endpoints to login users by emailing tokens to their email addresses instead of using passwords. Maildoor allows to define application specific behaviors as part of the authentication process. - - -## Installation - -This library is intended to be used as a dependency in your Go project. Installation implies go-getting the package with: - -```sh -go get github.com/wawandco/maildoor@latest -``` - -And then using it accordingly in your app. See the Usage section for detailed instructions on usage. -## Usage - -Maildoor instances satisfy the http.Handler interface and can be mounted into Mupliplexers. To initialize a Maildoor instance, use the New function: - -```go - // Initialize the maildoor handler to take care of the web requests. - auth, err := maildoor.NewWithOptions( - os.Getenv("SECRET_KEY"), - - maildoor.UseFinder(finder), - maildoor.UseTokenManager(maildoor.DefaultTokenManager(os.Getenv("SECRET_KEY"))), - maildoor.UseSender( - maildoor.NewSMTPSender(maildoor.SMTPOptions{ - From: os.Getenv("SMTP_FROM_EMAIL"), - Host: os.Getenv("SMTP_HOST"), // p.e. "smtp.gmail.com", - Port: os.Getenv("SMTP_PORT"), //"587", - Password: os.Getenv("SMTP_PASSWORD"), - }), - ), - ) - - if err != nil { - return nil, fmt.Errorf("error initializing maildoor: %w", err) - } -``` - -After initializing the Maildoor instance, you can mount it into a multiplexer: - -```go -mux := http.NewServeMux() -mux.Handle("/auth/", auth) // Set the prefix - -fmt.Println("Listening on port 8080") -if err := http.ListenAndServe(":8080", server); err != nil { - panic(fmt.Errorf("error starting server: %w", err)) -} -``` -### Options - -After seeing how to initialize the Maildoor Instance, lets dig a deeper into what some of these options mean. +Maildoor is an email based authentication library that allows users to sign up and sign in to your application using their email address. It is a pluggable library that can be used with any go http server. -#### FinderFn +### Usage -The finder function is used to find a user by email address. The logic for looking up users is up to the application developer, but it should return an `Emailable` instance to be used on the signin flow. The signature of the finder function is: +Using maildoor is as simple as creating a new instance of the maildoor.Handler and passing it to your http server. ```go -func(string) (Emailable, error) -``` - -Where the string is the email address or token to identify the user. -#### SenderFn - -Maildoor does not take care of sending your emails, instead it expects you to provide a function that will do this. This function will be called when a user requests a token to be sent to their email address and will be passed the message that needs to be send to the user. - -The sender function signature is: - -```go -func(*maildoor.Message) error -``` - -When this function returns an error the sign-in flow redirects the user to the login page with an error message. - -#### AfterLoginFn - -AfterLoginFn is a function that is called after a user has successfully logged in. It is passed the request instance, the response and user that has just logged in. Within this function typically the application does things like setting a session cookie and redirecting the user to a secure page. As with the sender function, its up to the application to decide what happens within the afterLogin function. - -Its signature is: - -```go -func(http.ResponseWriter, *http.Request, Emailable) error -``` - -#### LogoutFn - -Similar than the afterLogin function, the logout function is called after a user has successfully logged out. It is passed the request instance, the response and user that has just logged out. Within this function typically the application does things like clearing the session cookie and redirecting the landing page. As with the afterLoginFn function, it's up to the application to decide what happens within the logout function. - -Its signature is: - -```go -func(http.ResponseWriter, *http.Request) error -``` - -#### BaseURL - -The baseURL is the base URL where the app is running. By default its `http://localhost:8080` but you can override this value by setting the BaseURL option. - -#### Prefix - -Prefix of the maildoor routes, by default it is `/auth`. You can override this value by setting the Prefix option. When using a multiplexer, make sure to set the prefix to the same value as the one used in the maildoor instance. - -```go - -auth, err := maildoor.New(maildoor.Options{ -... - Prefix: "/auth", -... +// Initialize the maildoor handler +auth := maildoor.New( + maildoor.Logo("https://example.com/logo.png"), + maildoor.ProductName("My App")) + maildoor.Prefix("/auth/"), // Prefix for the routes + + // Defines the email sending mechanism which is up to the + // host application to implement. + maildoor.EmailSender(func(to, html, txt string) error{ + // send email + return nil + }), + + // Defines the email validation mechanism + maildoor.EmailValidator(func(email string) bool { + // validate email + return true + }), + + // Defines what to do after the user has successfuly logged in + // This is where you would set the user session or redirect to a private page + maildoor.AfterLogin(func w http.ResponseWriter, r http.Request) { + http.Redirect(w, r, "/private", http.StatusFound) + }), + + // Defines what to do after the user has successfuly loged out + // This is where you would clear the user session or redirect to a login page + maildoor.Logout(func(w http.ResponseWriter, r *http.Request){ + http.Redirect(w, r, "/auth/login", http.StatusFound) + }), }) -mux.Handle("/auth/", auth) // Correct -mux.Handle("/other/", auth) // Incorrect -``` - -#### Product - -Product allows to set some product related settings for the signin flow. This helps branding the pages rendered to the user. The product can specify the name of the product, the logo and the favicon. - -#### TokenManager - -TokenManager is a very important part of the authentication process. It is responsible for generating and validating tokens across the email authentication process. Maildoor provides a default implementation which uses JWT tokens, whether the application uses JWT or not, it should provide a token manager. A token manager should meet the TokenManager interface. - -```go -type TokenManager interface { - Generate(Emailable) (string, error) - Validate(string) (string, error) -} -``` - -To use the default token manager, you can use your key to build it: - -```go -maildoor.DefaultTokenManager(os.Getenv("TOKEN_MANAGER_SECRET")) -``` - -#### CSRFTokenSecret - -This option sets the secret used by the signin form to protect against CSRF attacks. We recommend to pull this value from an environment variable or secret storage. -#### Logger -Logger option allows application to set your own logger. If this is not specified Maildoor will use a muteLogger, which will not print anything out. There is a BasicLogger that can be used if needed. Also, if there is the need for a custom logger you can implement the Logger interface. - -```go -// Logger interface defines the minimum set of methods -// that a logger should satisfy to be used by the library. -type Logger interface { - // Log a message at the Info level. - Info(args ...interface{}) - - // Log a formatted message at the Info level. - Infof(format string, args ...interface{}) - - // Log a message at the Error level. - Error(args ...interface{}) - - // Log a formatted message at the Error level. - Errorf(format string, args ...interface{}) -} -``` - -### Login Workflow - -The following chart shows the authentication process flow followed by the Maildoor library. - -```mermaid -graph LR; - login(Login page)-->send(email sender); - send-->|User found or no error|sendemail(Email sent); - send-->|Error finding user|login; - sendemail-.-click(User Clicked link); - click-->verification(token verification); - verification-->|token expired|login; - verification-->|error verifying|login; - verification-->afterlogin(Application Afterlogin); -``` - -### The HTTP Endpoints - -Maildoor is an http.Handler, which means it receives requests and responds to them. The Maildoor handler is mounted on a prefix, which is set by the application developer. Under that prefix the handler responds to the following endpoints: - -#### GET:/auth/login -This is the login form. It renders a form with a CSRF token and a submit button. In here the user is asked to enter their email address. - -#### POST:/auth/send -This endpoint is hit by the login form. It receives the email address and the CSRF token from the user and upon confirmation with the `FinderFn` it sends a link with token to the user's email address. -#### GET:/auth/validate -This endpoint is where the email link is validated. It receives the token from the URL and it validates the token. If the token is valid, it runs the `AfterLoginFn` function. -#### DELETE:/auth/logout -This endpoint is intended to be used by the app to logout the user. It just run the `LogoutFn` function. - -#### GET:/assets/* -This endpoint serves static assets. It is mounted on the `/assets` prefix and it will serve all files from the `/assets` directory such as images and css needed for the form. - - -### Sample Application - -Within the sample folder you can find a go application that illustrates the usage of Maildoor. To run it from the command line you can use: - -```sh -go run ./sample/cmd/sample +mux := http.NewServeMux() +mux.Handle("/auth", auth) +mux.Handle("/private", secure(privateHandler)) +http.ListenAndServe(":8080", mux) ``` -## FAQ - -I do not use SMTP for sending, what should I do? -> Each application is free to send emails as it desires, in the sample application we use a [sendgrid](https://sendgrid.com/) SMTP authentication sender. - -How to I customize the email logo and product? -> These can be customized by setting the `Logo` and `Favicon` in the Product settings. - -Can I change the email copy (Subject or content)? -> Yes, you can change the subject and the content of the email. Maildoor will provide a Message struct that to your application implementation of the SenderFn, within there you can decide to change the subject and the content of the email. - -I don't want to use JWT for my tokens, what should I do? -> As long as you provide a TokenManager, Maildoor will use the token manager to generate and validate tokens. - -What should I do in the `AfterLoginFn` hook? -> Typically session and cookie management after login, but other things such as logging and threat detection can be done in there. - -How do I secure my application to prevent unauthorized access? -> Typically you would have a middleware that secures your private routes. Maildoor does not provide such middleware but it typically checks a session either in cookies or other persistence mean. - -## Guiding Principles - -- Use standard Go library as much as possible to avoid external dependencies. -- Application logic should live in the application, not in the library. -## TODO - -- [x] Add: Login flow diagram -- [x] Build: Default SMTPSender -- [x] Optimize: CSS to only be the one used (Tailwind CSS can do this) -- [x] Add: Login/sent screenshots -- [x] Add: Default afterLogin and logout hook functions (Cookie based) -- [x] Add: Secure cookie for the default afterLogin hook function. -- [ ] Design: Authentication Middleware ❓ -- [ ] Research: flash error messages instead of using parameters -- [ ] Add: Error pages (500 and 404) -- [ ] Design: Custom messages -- [ ] Design: Custom templates. +## Features +- Pluggable http.Handler that can be used with any go http server +- Customizable email sending mechanism +- Customizable email validation mechanism +- Customizable logo +- Customizable product name +### Roadmap +- Custom token storage mechanism +- Out of the box time bound token generation +- Customizable templates (Bring your own). +- Time based token expiration out the box +- Prevend CSRF attacks with token diff --git a/assets/images/favicon.png b/assets/images/favicon.png deleted file mode 100644 index 8feda2a..0000000 Binary files a/assets/images/favicon.png and /dev/null differ diff --git a/assets/images/favicon_dark.png b/assets/images/favicon_dark.png deleted file mode 100644 index fd04cca..0000000 Binary files a/assets/images/favicon_dark.png and /dev/null differ diff --git a/assets/images/maildoor_icon.png b/assets/images/maildoor_icon.png deleted file mode 100644 index 1e58e5c..0000000 Binary files a/assets/images/maildoor_icon.png and /dev/null differ diff --git a/assets/images/maildoor_icon_dark.png b/assets/images/maildoor_icon_dark.png deleted file mode 100644 index c9adc28..0000000 Binary files a/assets/images/maildoor_icon_dark.png and /dev/null differ diff --git a/assets/images/maildoor_logo_2.png b/assets/images/maildoor_logo_2.png deleted file mode 100644 index 71b0c83..0000000 Binary files a/assets/images/maildoor_logo_2.png and /dev/null differ diff --git a/assets/styles/maildoor.min.css b/assets/styles/maildoor.min.css deleted file mode 100644 index 882f2fc..0000000 --- a/assets/styles/maildoor.min.css +++ /dev/null @@ -1 +0,0 @@ -/*! tailwindcss v3.0.23 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}html{-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-size:100%;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}[multiple],[type=date],[type=datetime-local],[type=email],[type=month],[type=number],[type=password],[type=search],[type=tel],[type=text],[type=time],[type=url],[type=week],select,textarea{--tw-shadow:0 0 #0000;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:#fff;border-color:#6b7280;border-radius:0;border-width:1px;font-size:1rem;line-height:1.5rem;padding:.5rem .75rem}[multiple]:focus,[type=date]:focus,[type=datetime-local]:focus,[type=email]:focus,[type=month]:focus,[type=number]:focus,[type=password]:focus,[type=search]:focus,[type=tel]:focus,[type=text]:focus,[type=time]:focus,[type=url]:focus,[type=week]:focus,select:focus,textarea:focus{--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#2563eb;--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);border-color:#2563eb;box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);outline:2px solid #0000;outline-offset:2px}input::-moz-placeholder,textarea::-moz-placeholder{color:#6b7280;opacity:1}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#6b7280;opacity:1}input::placeholder,textarea::placeholder{color:#6b7280;opacity:1}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-date-and-time-value{min-height:1.5em}select{-webkit-print-color-adjust:exact;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3E%3C/svg%3E");background-position:right .5rem center;background-repeat:no-repeat;background-size:1.5em 1.5em;color-adjust:exact;padding-right:2.5rem}[multiple]{-webkit-print-color-adjust:unset;background-image:none;background-position:0 0;background-repeat:unset;background-size:initial;color-adjust:unset;padding-right:.75rem}[type=checkbox],[type=radio]{-webkit-print-color-adjust:exact;--tw-shadow:0 0 #0000;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:#fff;background-origin:border-box;border-color:#6b7280;border-width:1px;color:#2563eb;color-adjust:exact;display:inline-block;flex-shrink:0;height:1rem;padding:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;width:1rem}[type=checkbox]{border-radius:0}[type=radio]{border-radius:100%}[type=checkbox]:focus,[type=radio]:focus{--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:2px;--tw-ring-offset-color:#fff;--tw-ring-color:#2563eb;--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);outline:2px solid #0000;outline-offset:2px}[type=checkbox]:checked,[type=radio]:checked{background-color:currentColor;background-position:50%;background-repeat:no-repeat;background-size:100% 100%;border-color:#0000}[type=checkbox]:checked{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg viewBox='0 0 16 16' fill='%23fff' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M12.207 4.793a1 1 0 0 1 0 1.414l-5 5a1 1 0 0 1-1.414 0l-2-2a1 1 0 0 1 1.414-1.414L6.5 9.086l4.293-4.293a1 1 0 0 1 1.414 0z'/%3E%3C/svg%3E")}[type=radio]:checked{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg viewBox='0 0 16 16' fill='%23fff' xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='8' cy='8' r='3'/%3E%3C/svg%3E")}[type=checkbox]:checked:focus,[type=checkbox]:checked:hover,[type=checkbox]:indeterminate,[type=radio]:checked:focus,[type=radio]:checked:hover{background-color:currentColor;border-color:#0000}[type=checkbox]:indeterminate{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath stroke='%23fff' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3E%3C/svg%3E");background-position:50%;background-repeat:no-repeat;background-size:100% 100%}[type=checkbox]:indeterminate:focus,[type=checkbox]:indeterminate:hover{background-color:currentColor;border-color:#0000}[type=file]{background:unset;border-color:inherit;border-radius:0;border-width:0;font-size:unset;line-height:inherit;padding:0}[type=file]:focus{outline:1px auto -webkit-focus-ring-color}*,:after,:before{--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.mx-40{margin-left:10rem;margin-right:10rem}.mt-8{margin-top:2rem}.mb-24{margin-bottom:6rem}.mb-8{margin-bottom:2rem}.mt-6{margin-top:1.5rem}.mb-6{margin-bottom:1.5rem}.mb-4{margin-bottom:1rem}.mt-1{margin-top:.25rem}.block{display:block}.flex{display:flex}.table{display:table}.hidden{display:none}.h-full{height:100%}.h-20{height:5rem}.min-h-full{min-height:100%}.w-20{width:5rem}.w-full{width:100%}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.rounded{border-radius:.25rem}.rounded-lg{border-radius:.5rem}.border{border-width:1px}.border-2{border-width:2px}.border-red-300{--tw-border-opacity:1;border-color:rgb(252 165 165/var(--tw-border-opacity))}.border-gray-100{--tw-border-opacity:1;border-color:rgb(243 244 246/var(--tw-border-opacity))}.border-transparent{border-color:#0000}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity))}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity))}.bg-indigo-600{--tw-bg-opacity:1;background-color:rgb(79 70 229/var(--tw-bg-opacity))}.py-12{padding-bottom:3rem;padding-top:3rem}.px-4{padding-left:1rem;padding-right:1rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.px-8{padding-left:2rem;padding-right:2rem}.py-4{padding-bottom:1rem;padding-top:1rem}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-sans{font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-\[17px\]{font-size:17px}.text-sm{font-size:.875rem;line-height:1.25rem}.text-2xl{font-size:1.5rem;line-height:2rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-400:-ms-input-placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.placeholder-gray-400::placeholder{--tw-placeholder-opacity:1;color:rgb(156 163 175/var(--tw-placeholder-opacity))}.shadow-md{--tw-shadow:0 4px 6px -1px #0000001a,0 2px 4px -2px #0000001a;--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.shadow-md,.shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 2px 0 #0000000d;--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.hover\:bg-indigo-700:hover{--tw-bg-opacity:1;background-color:rgb(67 56 202/var(--tw-bg-opacity))}.focus\:border-indigo-500:focus{--tw-border-opacity:1;border-color:rgb(99 102 241/var(--tw-border-opacity))}.focus\:outline-none:focus{outline:2px solid #0000;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-indigo-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(99 102 241/var(--tw-ring-opacity))}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px}@media (min-width:640px){.sm\:mx-auto{margin-left:auto;margin-right:auto}.sm\:w-full{width:100%}.sm\:max-w-md{max-width:28rem}.sm\:rounded-lg{border-radius:.5rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:px-10{padding-left:2.5rem;padding-right:2.5rem}.sm\:text-sm{font-size:.875rem;line-height:1.25rem}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}} \ No newline at end of file diff --git a/buildtemplate.go b/buildtemplate.go deleted file mode 100644 index 2ea9897..0000000 --- a/buildtemplate.go +++ /dev/null @@ -1,58 +0,0 @@ -package maildoor - -import ( - "embed" - "fmt" - "html/template" - "io" - "path/filepath" - txtTemplate "text/template" -) - -var ( - //go:embed templates - templates embed.FS -) - -// buildTemplate for the passed template and data on a passed writer -// this is helpful to be able to render the templates in a generic way -// across different handlers. -func buildTemplate(tpath string, w io.Writer, data interface{}) error { - content, err := templates.ReadFile(tpath) - if err != nil { - return err - } - - // Non HTML templates do not use layouts. - if filepath.Ext(tpath) != ".html" { - t, err := txtTemplate.New(tpath).Parse(string(content)) - if err != nil { - return err - } - - return t.Execute(w, data) - } - - layout, err := templates.ReadFile("templates/layout.html") - if err != nil { - return err - } - - htmlTemplate, err := template.New("layout").Parse(string(layout)) - if err != nil { - return fmt.Errorf("error parsing layout template: %w", err) - } - - contents := fmt.Sprintf(`{{define "content"}}%s{{end}}`, string(content)) - htmlTemplate, err = template.Must(htmlTemplate.Clone()).Parse(contents) - if err != nil { - return fmt.Errorf("error parsing template %w", err) - } - - err = htmlTemplate.Execute(w, data) - if err != nil { - return err - } - - return nil -} diff --git a/cmd b/cmd new file mode 100755 index 0000000..d9ca361 Binary files /dev/null and b/cmd differ diff --git a/codes.go b/codes.go new file mode 100644 index 0000000..2bb3e69 --- /dev/null +++ b/codes.go @@ -0,0 +1,28 @@ +package maildoor + +import ( + "math/rand" + "sync" +) + +var ( + tux sync.Mutex + codes = map[string]string{} + letters = []rune("1234567890") +) + +// newCodeFor generates a new code for the email and stores it in the codes map. +// tokens are always 6 characters long. +func newCodeFor(email string) string { + // Generating a new token + b := make([]rune, 6) + for i := range b { + b[i] = letters[rand.Intn(len(letters))] + } + + tux.Lock() + defer tux.Unlock() + codes[email] = string(b) + + return string(b) +} diff --git a/cookie_valuer.go b/cookie_valuer.go deleted file mode 100644 index 918e1fa..0000000 --- a/cookie_valuer.go +++ /dev/null @@ -1,7 +0,0 @@ -package maildoor - -import "net/http" - -type CookieValuer interface { - CookieValue(r *http.Request) (string, error) -} diff --git a/defaulttokenmanager.go b/defaulttokenmanager.go deleted file mode 100644 index 2043e86..0000000 --- a/defaulttokenmanager.go +++ /dev/null @@ -1,20 +0,0 @@ -package maildoor - -import "time" - -// DefaultTokenManager is the default token manager which is -// an alias for a byte slice that will implement the TokenManager -// interface by using JWT. -type DefaultTokenManager []byte - -// Generate a JWT token that lasts for 30 minutes. The duration of the token -// is specified within the ExpiresAt claim. -func (dm DefaultTokenManager) Generate(user Emailable) (string, error) { - return GenerateJWT(30*time.Minute, []byte(dm)) -} - -// Validate the passed token and returns true if the token is valid. This implementation -// checks that the ExpiresAt claim to check that the token has not expired. -func (dm DefaultTokenManager) Validate(token string) (bool, error) { - return ValidateJWT(token, []byte(dm)) -} diff --git a/emailable.go b/emailable.go deleted file mode 100644 index a5ec8a1..0000000 --- a/emailable.go +++ /dev/null @@ -1,11 +0,0 @@ -package maildoor - -// Emailable is the type that will be returned from the -// finder, for maildoor to work it needs to be able to -// use a type that can provide an email address. -type Emailable interface { - // EmailAddress returns the email address of the user - // that will be authenticated. This address is used to - // send the authentication email to the user. - EmailAddress() string -} diff --git a/errors.go b/errors.go deleted file mode 100644 index f076cee..0000000 --- a/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package maildoor - -// ecodes holds the error messages for the supported error codes. -// these get rendered in the login page error box. -var ecodes = map[string]string{ - "E1": "πŸ˜₯ something happened while trying to find a user account with the given email. Please try again.", - "E2": "We're sorry, the specified token has already expired. Please enter your email again to receive a new one.", - "E3": "The token you have entered is invalid. Please enter your email again to receive a new one.", - "E4": "πŸ€” something was out of order with your previous login attempt. Please try again.", - "E5": "πŸ˜₯ something happened while attempting to send the login email. Please try again.", - "E6": "πŸ˜₯ an error occurred while generating authentication token. Please try again.", - "E7": "πŸ˜₯ an error occurred login in specified user. Please try again.", -} diff --git a/errtokenmanager_test.go b/errtokenmanager_test.go deleted file mode 100644 index 2338647..0000000 --- a/errtokenmanager_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package maildoor_test - -import ( - "fmt" - - "github.com/wawandco/maildoor" -) - -type errTokenManager string - -func (et errTokenManager) Generate(maildoor.Emailable) (string, error) { - return "", fmt.Errorf("%s", string(et)) -} - -func (et errTokenManager) Validate(tt string) (bool, error) { - return true, fmt.Errorf("%s", string(et)) -} diff --git a/go.mod b/go.mod index 60a5979..3b0e62c 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,3 @@ module github.com/wawandco/maildoor -go 1.17 - -require github.com/golang-jwt/jwt/v4 v4.2.0 +go 1.22 diff --git a/go.sum b/go.sum index ec4ea7a..e69de29 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +0,0 @@ -github.com/golang-jwt/jwt/v4 v4.2.0 h1:besgBTC8w8HjP6NzQdxwKH9Z5oQMZ24ThTrHp3cZ8eU= -github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= diff --git a/handle_code.go b/handle_code.go new file mode 100644 index 0000000..a891ac1 --- /dev/null +++ b/handle_code.go @@ -0,0 +1,40 @@ +package maildoor + +import ( + "context" + "net/http" +) + +// handleCode validates the input handleCode with the passed email. +func (m *maildoor) handleCode(w http.ResponseWriter, r *http.Request) { + email := r.FormValue("email") + code := r.FormValue("code") + + // Find a combination of token and email in the server + // call the afterlogin hook with the email + // remove the token from the server + if code != codes[email] { + data := atempt{ + Email: email, + Error: "Invalid token", + Logo: m.logoURL, + Icon: m.iconURL, + ProductName: m.productName, + } + + err := m.render(w, data, "layout.html", "handle_code.html") + if err != nil { + m.httpError(w, err) + + return + } + + return + } + + delete(codes, email) + + // Adding email to the context + r = r.WithContext(context.WithValue(r.Context(), "email", email)) + m.afterLogin(w, r) +} diff --git a/handle_code.html b/handle_code.html new file mode 100644 index 0000000..88dd494 --- /dev/null +++ b/handle_code.html @@ -0,0 +1,48 @@ +{{block "title" .}} {{.ProductName }} {{end}} + +{{define "yield"}} +
+
+ product logo +
+ +
+

+ Check your inbox +

+

+ We've sent you email message containing a six-digit login code to the {{.Email}} email address. +

+ Enter the login code to access your account. +

+ +
+ {{$action := "/code"}} +
+ +
+ + {{if ne .Error "" }} + + + + + + {{.Error}} + + {{end}} +
+ + +
+ +

+ {{$link := "/login"}} + Didn't get the message? Check your spam folder. Wrong email? Re-enter your address +

+
+
+
+{{end}} diff --git a/handle_email.go b/handle_email.go new file mode 100644 index 0000000..9e02378 --- /dev/null +++ b/handle_email.go @@ -0,0 +1,53 @@ +package maildoor + +import ( + "net/http" +) + +// handleEmail endpoint validates the handleEmail and sends a token to the +// user by calling the handleEmail sender function. +func (m *maildoor) handleEmail(w http.ResponseWriter, r *http.Request) { + data := atempt{ + Logo: m.logoURL, + ProductName: m.productName, + Icon: m.iconURL, + } + + email := r.FormValue("email") + if err := m.emailValidator(email); err != nil { + data.Error = err.Error() + w.WriteHeader(http.StatusUnprocessableEntity) + err := m.render(w, data, "layout.html", "handle_login.html") + if err != nil { + m.httpError(w, err) + } + + return + } + + token := newCodeFor(email) + html, txt, err := m.mailBodies(token) + if err != nil { + m.httpError(w, err) + return + } + + err = m.emailSender(email, html, txt) + if err != nil { + data.Error = err.Error() + w.WriteHeader(http.StatusInternalServerError) + err := m.render(w, data, "layout.html", "handle_login.html") + if err != nil { + m.httpError(w, err) + } + + return + } + + data.Email = email + err = m.render(w, data, "layout.html", "handle_code.html") + if err != nil { + m.httpError(w, err) + return + } +} diff --git a/handle_email_test.go b/handle_email_test.go new file mode 100644 index 0000000..f781f2e --- /dev/null +++ b/handle_email_test.go @@ -0,0 +1,96 @@ +package maildoor_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/wawandco/maildoor" + "github.com/wawandco/maildoor/internal/testhelpers" +) + +func TestHandleEmail(t *testing.T) { + // Test the handleEmail endpoint + t.Run("basic test", func(t *testing.T) { + auth := maildoor.New( + maildoor.EmailValidator(func(email string) error { + return nil + }), + + maildoor.EmailSender(func(email, html, txt string) error { + return nil + }), + ) + + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/email", nil) + req.Form = url.Values{ + "email": []string{"a@pagano.id"}, + } + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Check your inbox") + }) + + t.Run("invalid email", func(t *testing.T) { + auth := maildoor.New( + maildoor.EmailValidator(func(email string) error { + return errors.New("invalid email") + }), + ) + + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/email", nil) + req.Form = url.Values{ + "email": []string{"a@pagano.id"}, + } + + auth.ServeHTTP(w, req) + testhelpers.Equals(t, http.StatusUnprocessableEntity, w.Code) + testhelpers.Contains(t, w.Body.String(), "invalid email") + }) + + t.Run("error sending email", func(t *testing.T) { + auth := maildoor.New( + maildoor.EmailValidator(func(email string) error { + return nil + }), + + maildoor.EmailSender(func(email, html, txt string) error { + return errors.New("error sending email") + }), + ) + + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/email", nil) + + auth.ServeHTTP(w, req) + testhelpers.Equals(t, http.StatusInternalServerError, w.Code) + testhelpers.Contains(t, w.Body.String(), "error sending email") + }) + + t.Run("calls sending email", func(t *testing.T) { + var textMessage string + auth := maildoor.New( + maildoor.EmailValidator(func(email string) error { + return nil + }), + + maildoor.EmailSender(func(email, html, txt string) error { + textMessage = txt + return nil + }), + ) + + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/email", nil) + + auth.ServeHTTP(w, req) + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, textMessage, "Code:") + }) +} diff --git a/handle_login.go b/handle_login.go new file mode 100644 index 0000000..89b2055 --- /dev/null +++ b/handle_login.go @@ -0,0 +1,22 @@ +package maildoor + +import ( + "net/http" +) + +// handleLogin enpoint renders the handleLogin page to enter the user +// identifier. +func (m *maildoor) handleLogin(w http.ResponseWriter, r *http.Request) { + data := atempt{ + Logo: m.logoURL, + Icon: m.iconURL, + ProductName: m.productName, + } + + err := m.render(w, data, "layout.html", "handle_login.html") + if err != nil { + m.httpError(w, err) + + return + } +} diff --git a/handle_login.html b/handle_login.html new file mode 100644 index 0000000..f02fdbf --- /dev/null +++ b/handle_login.html @@ -0,0 +1,47 @@ +{{block "title" .}} {{.ProductName }}{{end}} + +{{define "yield"}} +
+
+ product logo +
+ +
+

+ Sign in to your account +

+ +

+ Please enter the email address associated with your account, + our system will send an access code to that address upon successful + identification of your account. +

+ + {{$action := "/email"}} +
+ +
+ +
+ + {{if ne .Error "" }} + + + + + + {{.Error}} + + {{end}} +
+
+ +
+ +
+
+
+
+{{end}} diff --git a/handle_login_test.go b/handle_login_test.go new file mode 100644 index 0000000..87d1e38 --- /dev/null +++ b/handle_login_test.go @@ -0,0 +1,107 @@ +package maildoor_test + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/wawandco/maildoor" + "github.com/wawandco/maildoor/internal/testhelpers" +) + +func TestHandleLogin(t *testing.T) { + t.Run("basic", func(t *testing.T) { + auth := maildoor.New() + w := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/login", nil) + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + }) + + t.Run("not extra path", func(t *testing.T) { + auth := maildoor.New() + req := httptest.NewRequest("GET", "/login/other-thing", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + testhelpers.Equals(t, http.StatusNotFound, w.Code) + }) + + t.Run("using prefix", func(t *testing.T) { + auth := maildoor.New(maildoor.Prefix("/auth")) + req := httptest.NewRequest("GET", "/auth/login", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + }) + + t.Run("using logo", func(t *testing.T) { + auth := maildoor.New( + maildoor.Prefix("/auth"), + maildoor.Logo("https://my.logo/image.png"), + ) + req := httptest.NewRequest("GET", "/auth/login", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + testhelpers.Contains(t, w.Body.String(), "https://my.logo/image.png") + }) + + t.Run("using icon", func(t *testing.T) { + auth := maildoor.New( + maildoor.Prefix("/auth"), + maildoor.Icon("https://my.icon/image.png"), + ) + req := httptest.NewRequest("GET", "/auth/login", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + testhelpers.Contains(t, w.Body.String(), "https://my.icon/image.png") + }) + + t.Run("using product name", func(t *testing.T) { + auth := maildoor.New( + maildoor.Prefix("/auth"), + maildoor.ProductName("My App"), + ) + req := httptest.NewRequest("GET", "/auth/login", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + testhelpers.Contains(t, w.Body.String(), "My App") + }) + + t.Run("using all options", func(t *testing.T) { + auth := maildoor.New( + maildoor.Prefix("/auth"), + maildoor.Logo("https://my.logo/image.png"), + maildoor.Icon("https://my.icon/image.png"), + maildoor.ProductName("My App"), + ) + req := httptest.NewRequest("GET", "/auth/login", nil) + w := httptest.NewRecorder() + + auth.ServeHTTP(w, req) + + testhelpers.Equals(t, http.StatusOK, w.Code) + testhelpers.Contains(t, w.Body.String(), "Sign in to your account") + testhelpers.Contains(t, w.Body.String(), "https://my.logo/image.png") + testhelpers.Contains(t, w.Body.String(), "https://my.icon/image.png") + testhelpers.Contains(t, w.Body.String(), "My App") + }) +} diff --git a/handle_logout.go b/handle_logout.go new file mode 100644 index 0000000..c3477f5 --- /dev/null +++ b/handle_logout.go @@ -0,0 +1,11 @@ +package maildoor + +import ( + "net/http" +) + +// handleLogin enpoint renders the handleLogin page to enter the user +// identifier. +func (m *maildoor) handleLogout(w http.ResponseWriter, r *http.Request) { + m.logout(w, r) +} diff --git a/handler.go b/handler.go deleted file mode 100644 index 9cbf464..0000000 --- a/handler.go +++ /dev/null @@ -1,103 +0,0 @@ -package maildoor - -import ( - "net/http" - "path" - "strings" -) - -// handler takes care of processing different actions against the maildoor -// server, such as login, send, validate, logout, most of these involve calling -// the corresponding functions provided by the host application. -type handler struct { - prefix string - baseURL string - csrfTokenSecret string - - // Product settings - product productConfig - - finderFn func(token string) (Emailable, error) - senderFn func(message *Message) error - afterLoginFn func(w http.ResponseWriter, r *http.Request, user Emailable) error - logoutFn func(w http.ResponseWriter, r *http.Request) error - - tokenManager TokenManager - logger Logger - - // Serves the static assets such as css and images - assetsServer http.Handler - - valueEncoder valueEncoder -} - -func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h.logger.Info(r.Method, ":", r.URL.Path) - - r.URL.Path = strings.TrimSuffix(r.URL.Path, "/") - if !strings.HasPrefix(r.URL.Path, h.prefix) { - r.URL.Path = path.Join(h.prefix, r.URL.Path) - } - - err := r.ParseForm() - if err != nil { - h.logger.Errorf("error parsing form: %v", err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Overriding the request method to allow for browsers - // to do DELETE/PATCH/PUT requests. - if r.Form.Get("_method") != "" { - h.logger.Infof("Request method upgraded to be %v", r.Form.Get("_method")) - r.Method = r.Form.Get("_method") - } - - if r.URL.Path == h.prefix { - http.Redirect(w, r, path.Join(h.prefix, "/login/"), http.StatusFound) - return - } - - if r.URL.Path == path.Join(h.prefix, "/login/") && r.Method == http.MethodGet { - h.login(w, r) - - return - } - - if r.URL.Path == path.Join(h.prefix, "/send/") && r.Method == http.MethodPost { - h.send(w, r) - - return - } - - if r.URL.Path == path.Join(h.prefix, "/validate/") && r.Method == http.MethodGet { - h.validate(w, r) - - return - } - - if r.URL.Path == path.Join(h.prefix, "/logout/") && r.Method == http.MethodDelete { - h.logout(w, r) - - return - } - - if strings.HasPrefix(r.URL.Path, path.Join(h.prefix, "assets")) && r.Method == http.MethodGet { - // Trimming the prefix to get the path of the asset - r.URL.Path = strings.Replace(r.URL.Path, path.Join(h.prefix), "", 1) - h.assetsServer.ServeHTTP(w, r) - - return - } - - http.NotFound(w, r) -} - -func (h handler) CookieValue(r *http.Request) (string, error) { - v, err := r.Cookie(DefaultCookieName) - if err != nil { - return "", err - } - - return h.valueEncoder.Decode(v.Value) -} diff --git a/internal/sample/auth.go b/internal/sample/auth.go new file mode 100644 index 0000000..4d322a4 --- /dev/null +++ b/internal/sample/auth.go @@ -0,0 +1,106 @@ +package sample + +import ( + "bytes" + _ "embed" + "errors" + "fmt" + "net/http" + "net/smtp" + "os" + "text/template" + "time" + + "github.com/wawandco/maildoor" +) + +// Auth handler with custom email validator +// and after login function +var Auth = maildoor.New( + maildoor.Prefix("/auth/"), + maildoor.Icon("https://raw.githubusercontent.com/wawandco/maildoor/5de0561/internal/sample/logo.png"), + maildoor.Logo("https://raw.githubusercontent.com/wawandco/maildoor/5de0561/internal/sample/logo.png"), + maildoor.ProductName("Basse"), + maildoor.EmailValidator(validateEmail), + maildoor.AfterLogin(afterLogin), + maildoor.EmailSender(sendEmail), + maildoor.Logout(logout), +) + +// email struct to hold the email data to be used +// with the email template +type email struct { + From string + To string + Subject string + HTML string + Text string +} + +//go:embed email_template.txt +var mtmpl string + +// emailTmpl is the template to be used to send the email +var emailTmpl = template.Must(template.New("email").Parse(mtmpl)) + +// sendEmail function to send the multipart email to the user +func sendEmail(to, html, txt string) error { + from := os.Getenv("SMTP_FROM") + password := os.Getenv("SMTP_PASS") + user := os.Getenv("SMTP_USER") + + mb := bytes.NewBuffer([]byte{}) + err := emailTmpl.Execute(mb, email{ + HTML: html, + Text: txt, + From: from, + To: to, + Subject: "Your authentication code", + }) + + if err != nil { + return fmt.Errorf("error executing email template: %w", err) + } + + auth := smtp.PlainAuth("", user, password, "smtp.resend.com") + err = smtp.SendMail("smtp.resend.com:587", auth, from, []string{to}, mb.Bytes()) + if err != nil { + return fmt.Errorf("error sending smtp message: %w", err) + } + + return nil +} + +// afterLogin function to redirect the user to the private area +func afterLogin(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: "sample", + Value: "sample", + Expires: time.Now().Add(24 * time.Hour), + Path: "/", + }) + + http.Redirect(w, r, "/private", http.StatusFound) +} + +// validateEmail function to validate the email address +// in this case we are only allowing a@pagano.id +func validateEmail(email string) error { + if email == "a@pagano.id" { + return nil + } + + return errors.New("invalid email address") +} + +// Logout clear the cookie and redirects to the root +func logout(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: "sample", + Value: "", + Expires: time.Now().Add(-1 * time.Hour), + Path: "/", + }) + + http.Redirect(w, r, "/", http.StatusFound) +} diff --git a/internal/sample/cmd/main.go b/internal/sample/cmd/main.go new file mode 100644 index 0000000..ffab4aa --- /dev/null +++ b/internal/sample/cmd/main.go @@ -0,0 +1,22 @@ +package main + +import ( + "log/slog" + "net/http" + + "github.com/wawandco/maildoor/internal/sample" +) + +func main() { + r := http.NewServeMux() + + // Auth handlers + r.Handle("/auth/", sample.Auth) + + // Application handlers + r.HandleFunc("/private", sample.Private) + r.HandleFunc("/{$}", sample.Home) + + slog.Info("Server running on :3000") + http.ListenAndServe(":3000", r) +} diff --git a/internal/sample/email_template.txt b/internal/sample/email_template.txt new file mode 100644 index 0000000..ba5fa05 --- /dev/null +++ b/internal/sample/email_template.txt @@ -0,0 +1,14 @@ +From: {{.From}} +To: {{.To}} +Subject: {{.Subject}} +Content-Type: multipart/alternative; boundary="edd17d2fef7afe7e200012b29769cabc07d4281c681e6132bb9eaefb854c" + +--edd17d2fef7afe7e200012b29769cabc07d4281c681e6132bb9eaefb854c +Content-Type: text/plain; charset="utf-8" + +{{.Text}} +--edd17d2fef7afe7e200012b29769cabc07d4281c681e6132bb9eaefb854c +Content-Type: text/html; charset="utf-8" + +{{.HTML}} +--edd17d2fef7afe7e200012b29769cabc07d4281c681e6132bb9eaefb854c-- diff --git a/internal/sample/home.go b/internal/sample/home.go new file mode 100644 index 0000000..b954536 --- /dev/null +++ b/internal/sample/home.go @@ -0,0 +1,14 @@ +package sample + +import ( + _ "embed" + "net/http" +) + +//go:embed home.html +var home []byte + +// Simple home handler with link to the login page +func Home(w http.ResponseWriter, r *http.Request) { + w.Write(home) +} diff --git a/internal/sample/home.html b/internal/sample/home.html new file mode 100644 index 0000000..7a9833a --- /dev/null +++ b/internal/sample/home.html @@ -0,0 +1,17 @@ + + + + + + + Sample: Home Page + + + +
+

Public Page

+

This is the public space, if you want to go to the secure page you need to login.

+ Login +
+ + diff --git a/internal/sample/logo.png b/internal/sample/logo.png new file mode 100644 index 0000000..6a05a29 Binary files /dev/null and b/internal/sample/logo.png differ diff --git a/internal/sample/private.go b/internal/sample/private.go new file mode 100644 index 0000000..69235a7 --- /dev/null +++ b/internal/sample/private.go @@ -0,0 +1,20 @@ +package sample + +import ( + _ "embed" + "net/http" +) + +//go:embed private.html +var private []byte + +// Private handler to show the private content to the user +func Private(w http.ResponseWriter, r *http.Request) { + _, err := r.Cookie("sample") + if err != nil { + http.Redirect(w, r, "/auth/login", http.StatusFound) + return + } + + w.Write(private) +} diff --git a/internal/sample/private.html b/internal/sample/private.html new file mode 100644 index 0000000..a889a2a --- /dev/null +++ b/internal/sample/private.html @@ -0,0 +1,21 @@ + + + + + + + Sample: Home Page + + + +
+

πŸ”’ Private Section

+

This is the private space, means you were able to login!

+ +
+ + +
+
+ + diff --git a/jwt.go b/jwt.go deleted file mode 100644 index 20a57ec..0000000 --- a/jwt.go +++ /dev/null @@ -1,49 +0,0 @@ -package maildoor - -import ( - "fmt" - "strings" - "time" - - "github.com/golang-jwt/jwt/v4" -) - -// GenerateJWT token with the specified duration and secret. -func GenerateJWT(d time.Duration, secret []byte) (string, error) { - expiration := time.Now().Add(d).Format(time.RFC3339) - t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "ExpiresAt": expiration, - }) - - return t.SignedString(secret) -} - -// ValidateJWT token with the specified secret. -func ValidateJWT(tt string, secret []byte) (bool, error) { - tokenString := strings.TrimSpace(tt) - t, err := jwt.ParseWithClaims(tokenString, &jwt.MapClaims{}, jwtKeyFunc(secret)) - - if err != nil { - return false, fmt.Errorf("error parsing error: %w", err) - } - - cl := t.Claims.(*jwt.MapClaims) - expires, err := time.Parse(time.RFC3339, (*cl)["ExpiresAt"].(string)) - - if err != nil || expires.Before(time.Now()) { - return false, nil - } - - return err == nil, err -} - -func jwtKeyFunc(key []byte) func(token *jwt.Token) (interface{}, error) { - return func(token *jwt.Token) (interface{}, error) { - _, ok := token.Method.(*jwt.SigningMethodHMAC) - if !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - - return key, nil - } -} diff --git a/layout.html b/layout.html new file mode 100644 index 0000000..c134df9 --- /dev/null +++ b/layout.html @@ -0,0 +1,27 @@ + + + + + + + + {{block "title" .}}Maildoor{{end}} + + + + + + +
+ {{block "yield" .}}{{end}} +
+ + diff --git a/logger.go b/logger.go deleted file mode 100644 index 7c71701..0000000 --- a/logger.go +++ /dev/null @@ -1,55 +0,0 @@ -package maildoor - -import "log" - -var ( - // default logger is a mute logger as we don't - // want to spam the logs unless explicitly told by - // the user. - defaultLogger Logger = muteLogger(1) - - // BasicLogger is a simple logger that prints to stdout - // using the `log` package. - BasicLogger = stdOutLogger(2) -) - -// Logger interface defines the minimum set of methods -// that a logger should satisfy to be used by the library. -type Logger interface { - // Log a message at the Info level. - Info(args ...interface{}) - - // Log a formatted message at the Info level. - Infof(format string, args ...interface{}) - - // Log a message at the Error level. - Error(args ...interface{}) - - // Log a formatted message at the Error level. - Errorf(format string, args ...interface{}) -} - -type muteLogger int - -func (l muteLogger) Info(args ...interface{}) {} -func (l muteLogger) Infof(format string, args ...interface{}) {} -func (l muteLogger) Error(args ...interface{}) {} -func (l muteLogger) Errorf(format string, args ...interface{}) {} - -type stdOutLogger int - -func (l stdOutLogger) Info(args ...interface{}) { - log.Print("level=info ", args) -} - -func (l stdOutLogger) Infof(format string, args ...interface{}) { - log.Printf("level=info "+format, args) -} - -func (l stdOutLogger) Error(args ...interface{}) { - log.Print("level=info ", args) -} - -func (l stdOutLogger) Errorf(format string, args ...interface{}) { - log.Printf("level=info "+format, args) -} diff --git a/logger_test.go b/logger_test.go deleted file mode 100644 index 44e0a24..0000000 --- a/logger_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package maildoor_test - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/wawandco/maildoor" - "github.com/wawandco/maildoor/internal/testhelpers" -) - -// stringLogger is a logger that writes to a string -// it serves as a way to demonstrate how to implement -// a custom logger if the application needs to log to -// other than stdout. -type stringLogger struct { - content string -} - -func (sl *stringLogger) Info(els ...interface{}) { - sl.content += "level=info " - sl.content += fmt.Sprint(els...) - sl.content += "\n" -} - -func (sl *stringLogger) Infof(format string, args ...interface{}) { - sl.content += fmt.Sprintf("level=info %v \n"+format, args...) -} - -func (sl *stringLogger) Error(els ...interface{}) { - sl.content += "level=error " - sl.content += fmt.Sprint(els...) - sl.content += "\n" -} - -func (sl *stringLogger) Errorf(format string, args ...interface{}) { - sl.content += fmt.Sprintf("level=error %v \n"+format, args...) -} - -func TestCustomLogger(t *testing.T) { - lg := &stringLogger{} - h, err := maildoor.NewWithOptions("secret", maildoor.UseLogger(lg)) - - testhelpers.NoError(t, err) - w := httptest.NewRecorder() - - req := httptest.NewRequest(http.MethodGet, "/auth/login/", nil) - h.ServeHTTP(w, req) - testhelpers.Equals(t, http.StatusOK, w.Code) - - testhelpers.Contains(t, lg.content, "level=info") - testhelpers.Contains(t, lg.content, "/auth/login") -} diff --git a/login.go b/login.go deleted file mode 100644 index d9008d9..0000000 --- a/login.go +++ /dev/null @@ -1,43 +0,0 @@ -package maildoor - -import ( - "net/http" -) - -// login function renders the login page, it also renders conditionally -// errors because when some of the other endpoints fail, it will redirect -// to this page. -func (h handler) login(w http.ResponseWriter, r *http.Request) { - token, err := GenerateJWT(csrfDuration, []byte(h.csrfTokenSecret)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - data := struct { - Title string - Action string - Logo string - Favicon string - CSRFToken string - Error string - - StylesPath string - }{ - Title: "Login Page", - Action: h.sendPath(), - Logo: h.product.LogoURL, - Favicon: h.product.FaviconURL, - CSRFToken: token, - Error: ecodes[r.Form.Get("error")], - - StylesPath: h.stylesPath(), - } - - err = buildTemplate("templates/login.html", w, data) - - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } -} diff --git a/login_test.go b/login_test.go deleted file mode 100644 index 8c810c4..0000000 --- a/login_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package maildoor_test - -import ( - "net/http" - "net/http/httptest" - "regexp" - "testing" - - "github.com/wawandco/maildoor" - "github.com/wawandco/maildoor/internal/testhelpers" -) - -func TestLogin(t *testing.T) { - h, err := maildoor.NewWithOptions("secret") - - testhelpers.NoError(t, err) - - t.Run("Content", func(tt *testing.T) { - req := httptest.NewRequest(http.MethodGet, "/auth/login/", nil) - w := httptest.NewRecorder() - - h.ServeHTTP(w, req) - testhelpers.Equals(tt, http.StatusOK, w.Code) - - content := w.Body.String() - - testhelpers.Contains(tt, content, "Welcome Back πŸ‘‹") - testhelpers.Contains(tt, content, "/auth/send") - testhelpers.Contains(tt, content, ``) - }, - }, - - { - name: "Invalid Error", - url: "/auth/login/?err=SOMETHING", - val: func(t *testing.T, content string) { - testhelpers.NotContains(tt, content, `