Skip to content
This repository has been archived by the owner on Nov 5, 2020. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
zrrrzzt committed Mar 16, 2017
1 parent 277d40a commit 1049d72
Show file tree
Hide file tree
Showing 21 changed files with 555 additions and 0 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
47 changes: 47 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# IDE
.idea
.vscode

# Mac OS
.DS_Store

# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

# yarn
yarn.lock
6 changes: 6 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
language: node_js
node_js:
- "7"
after_success:
- npm run coveralls
- test $TRAVIS_BRANCH = "master" && npm i -g now && now -t=$NOW_TOKEN --npm && now -t=$NOW_TOKEN alias
26 changes: 26 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
###########################################################
#
# Dockerfile for micro-auth-ldap
#
###########################################################

# Setting the base to nodejs 7.7.3
FROM node:7.7.3-alpine

# Maintainer
MAINTAINER Geir Gåsodden

# Bundle app source
COPY . /src

# Change working directory
WORKDIR "/src"

# Install dependencies
RUN npm install --production

# Expose 3000
EXPOSE 3000

# Startup
ENTRYPOINT npm start
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Telemark fylkeskommune

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,38 @@
[![Build Status](https://travis-ci.org/telemark/micro-auth-ldap.svg?branch=master)](https://travis-ci.org/telemark/micro-auth-ldap)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
[![Greenkeeper badge](https://badges.greenkeeper.io/telemark/micro-auth-ldap.svg)](https://greenkeeper.io/)

# micro-auth-mock

Mocks the auth service

## config docker.env

```bash
JWT_SECRET=Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go
ENCRYPTOR_SECRET=Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go
SESSION_STORAGE_URL=https://tmp.storage.micro.t-fk.no
```

## API

### GET ```/login?origin=<url for redirect>```

- returns loginform
- successful login redirects to ```origin?jwt=<jwt>```

### POST ```/auth```

-post username, password and origin
- successful auth redirects to ```origin?jwt=<jwt>```

### GET ```/?jwt=<jwt>```

- jwt needs userName and origin
- successful lookup of user redirects to ```origin?jwt=<jwt>```

## License

[MIT](LICENSE)

![alt text](https://robots.kebabstudios.party/micro-auth-mock.png "Robohash image of micro-auth-mock")
33 changes: 33 additions & 0 deletions config/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict'

const fs = require('fs')
const path = require('path')

function ldapTlsSettings () {
let config = false

if (process.env.LDAP_TLS_SETTINGS) {
config = {
rejectUnauthorized: process.env.LDAP_TLS_REJECT_UNAUTHORIZED ? true : false, // eslint-disable-line no-unneeded-ternary
ca: [
fs.readFileSync(path.join(__dirname, process.env.LDAP_TLS_CA_PATH))
]
}
}

return config
}

module.exports = {
JWT_SECRET: process.env.JWT_SECRET || 'Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go',
ENCRYPTOR_SECRET: process.env.ENCRYPTOR_SECRET || 'Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go',
SESSION_STORAGE_URL: process.env.SESSION_STORAGE_URL || 'https://tmp.storage.service.t-fk.no',
LDAP: {
url: process.env.LDAP_URL || 'ldap://ldap.forumsys.com:389',
bindDn: process.env.LDAP_BIND_DN || 'cn=read-only-admin,dc=example,dc=com',
bindCredentials: process.env.LDAP_BIND_CREDENTIALS || 'password',
searchBase: process.env.LDAP_SEARCH_BASE || 'dc=example,dc=com',
searchFilter: process.env.LDAP_SEARCH_FILTER || '(uid={{username}})',
tlsOptions: ldapTlsSettings()
}
}
4 changes: 4 additions & 0 deletions docker.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
NODE_ENV=production
JWT_SECRET=Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go
ENCRYPTOR_SECRET=Louie Louie, oh no, I got to go Louie Louie, oh no, I got to go
SESSION_STORAGE_URL=https://tmp.storage.micro.t-fk.no
77 changes: 77 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
'use strict'

const readFileSync = require('fs').readFileSync
const jwt = require('jsonwebtoken')
const marked = require('marked')
const { parse } = require('url')
const { json, send } = require('micro')
const config = require('./config')
const bodyParser = require('urlencoded-body-parser')
const loginPage = require('./lib/render-login-page')
const lookupUser = require('./lib/lookup-user')
const saveSession = require('./lib/save-session')
const loginUser = require('./lib/login-user')
const generateJwt = require('./lib/generate-jwt')

function addNextPath (data) {
let nextPath = ''
if (data.nextPath && data.nextPath.length > 0) {
nextPath = `&nextPath=${data.nextPath}`
}
return nextPath
}

module.exports = async (request, response) => {
const {pathname, query} = await parse(request.url, true)
if (pathname === '/auth') {
const data = request.method === 'POST' ? await bodyParser(request) : query
try {
const result = await loginUser(data)
const session = await saveSession(result)
const jwt = generateJwt(Object.assign({sessionKey: session}, result))
const url = `${data.origin}?jwt=${jwt}${addNextPath(data)}`
response.writeHead(302, { Location: url })
response.end()
} catch (error) {
console.error(error)
const errorMessage = typeof error === 'string' ? error : error.message || 'Unknown error'
const em = /80090308/.test(errorMessage) ? 'Ugyldig brukernavn eller passord' : encodeURIComponent(errorMessage)
const url = `/login?origin=${data.origin}${addNextPath(data)}&error=${em}`
response.writeHead(302, { Location: url })
response.end()
}
} else if (query.jwt) {
const receivedToken = query.jwt
jwt.verify(receivedToken, config.JWT_SECRET, async (error, data) => {
if (error) {
console.error(error)
send(response, 500, error)
} else {
try {
const result = await lookupUser(data)
const session = await saveSession(result)
const jwt = generateJwt(Object.assign({sessionKey: session}, result))
const url = `${data.origin}?jwt=${jwt}${addNextPath(query)}`
response.writeHead(302, { Location: url })
response.end()
} catch (error) {
console.error(error)
send(response, 500, error)
}
}
})
} else if (pathname === '/login') {
const data = request.method === 'POST' ? await json(request) : query
if (data.origin) {
response.setHeader('Content-Type', 'text/html')
send(response, 200, loginPage(data))
} else {
send(response, 500, {error: 'missing required param: origin'})
}
} else {
response.setHeader('Content-Type', 'text/html')
const readme = readFileSync('./README.md', 'utf-8')
const html = marked(readme)
send(response, 200, html)
}
}
22 changes: 22 additions & 0 deletions lib/generate-jwt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict'

const config = require('../config')
const jwt = require('jsonwebtoken')
const encryptor = require('simple-encryptor')(config.ENCRYPTOR_SECRET)

module.exports = data => {
const tokenOptions = {
expiresIn: '1h',
issuer: 'https://auth.t-fk.no'
}
const tokenData = {
data: encryptor.encrypt({
userName: data.displayName || data.cn,
userId: data.sAMAccountName || data.uid || '',
session: data.sessionKey
})
}
const token = jwt.sign(tokenData, config.JWT_SECRET, tokenOptions)

return token
}
11 changes: 11 additions & 0 deletions lib/login-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
'use strict'

module.exports = data => {
return new Promise((resolve, reject) => {
const user = {
cn: 'Mock Mr Mock',
uid: data.username
}
resolve(user)
})
}
81 changes: 81 additions & 0 deletions lib/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html lang="no">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- load MUI -->
<link href="https://cdn.muicss.com/mui-0.9.10/css/mui.min.css" rel="stylesheet" type="text/css" />
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" />
<script src="https://cdn.muicss.com/mui-0.9.10/js/mui.min.js"></script>
<title>Pålogging Telemark fylkeskommune</title>
</head>
<body>
<div class="wrapper">
<div class="mui-panel mui-text-center login">
<form action="/auth" method="POST" enctype="application/x-www-form-urlencoded" class="mui-form">
<input type="hidden" name="origin" value="{{origin}}"/>
<input type="hidden" name="nextPath" value="{{nextPath}}"/>
<img src="https://www.telemark.no/bundles/tfktelemark/images/logo/logo.svg" alt="Telemark fylkeskommune logo">
<h5>Logg inn</h5>
<p class="desc">Telemark fylkeskommune</p>
<div class="mui-textfield">
<input type="text" name="username" required autofocus>
<label>Brukernavn</label>
</div>
<div class="mui-textfield">
<input type="password" name="password" required>
<label>Passord</label>
</div>
<span class="error">{{error}}</span>
<button type="submit" class="mui-btn mui-btn--raised">Logg inn</button>
</form>
</div>
</div>

<style>
body {
font-family: "Roboto", "Georgia", "Times", "Times New Roman", serif !important;
background: #ffd520;
color: #000;
}
button.mui-btn {
background: #6ac4ae;
color: white;
width: 100%;
text-align: center;
}
button.mui-btn:hover {
background: #ffd520;
color: black;
}
h5 {
font-size: 2.4rem;
font-weight: 400;
}
.wrapper {
margin-top: 4em;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.login {
width: 350px;
}
.desc {
color: #757575;
padding-bottom: 15px;
}
.mui-textfield>input:focus, .mui-textfield>textarea:focus {
border-color: #6ac4ae;
}
.mui-textfield>input:focus~label, .mui-textfield>textarea:focus~label {
color: #6ac4ae;
}
.error {
color: red
}
</style>
</body>
</html>
9 changes: 9 additions & 0 deletions lib/lookup-user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use strict'

module.exports = async data => {
const user = {
cn: 'Mock Mr Mock',
uid: data.username
}
return user
}
Loading

0 comments on commit 1049d72

Please sign in to comment.