Ubuntu

first commit

Showing 49 changed files with 729 additions and 0 deletions
# DropBox Project using AWS, Khuloud
### 경희대학교 Cloud Computing A조
## 팀원
- 2017110267 강연욱
- 2017103972 김성연
- 2017100907 유정수
- 2017104025 정수연
- 2016104173 최재혁
## 기술 Stack
1. Frontend: nuxt, vuetify
2. Backend : Django
3. Database: DynamoDB
4. A W S : EC2, S3
## 향후 일정
\ No newline at end of file
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class BlogConfig(AppConfig):
name = 'blog'
No preview for this file type
import boto3
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
class Cognito():
region = config['cognito']['region']
user_pool_id = config['cognito']['user_pool_id']
app_client_id = config['cognito']['app_client_id']
identity_pool_id = config['cognito']['identity_pool_id']
account_id = config['cognito']['account_id']
token = ''
def sign_up(self, username, password, UserAttributes):
client = boto3.client('cognito-idp', self.region,
aws_access_key_id=config['aws']['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY'])
response = client.sign_up(ClientId=self.app_client_id,
Username=username,
Password=password,
UserAttributes=UserAttributes)
return response
def confirm_sign_up(self, username):
client = boto3.client('cognito-idp', self.region,
aws_access_key_id=config['aws']['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY'])
response = client.admin_confirm_sign_up(UserPoolId=self.user_pool_id, Username=username)
return response
def sign_in_admin(self, username, password):
# Get ID Token
idp_client = boto3.client('cognito-idp', self.region,
aws_access_key_id=config['aws']['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY'])
response = idp_client.admin_initiate_auth(UserPoolId=self.user_pool_id,
ClientId=self.app_client_id,
AuthFlow='ADMIN_NO_SRP_AUTH',
AuthParameters={'USERNAME': username,'PASSWORD': password})
provider = 'cognito-idp.%s.amazonaws.com/%s' % (self.region, self.user_pool_id)
self.token = response['AuthenticationResult']['IdToken']
# Get IdentityId
ci_client = boto3.client('cognito-identity', self.region,
aws_access_key_id=config['aws']['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY'])
response = ci_client.get_id(AccountId=self.account_id,
IdentityPoolId=self.identity_pool_id,
Logins={provider: self.token})
# Get Credentials
response = ci_client.get_credentials_for_identity(IdentityId=response['IdentityId'], Logins={provider: self.token})
return response
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
No preview for this file type
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock%}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
\ No newline at end of file
<h1>
hi!
</h1>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>KHUropBox</title>
<script src="/static/js/app.js"></script>
<script src="/static/js/aws-sdk.min.js"></script>
<link href="/static/css/app.css" rel="stylesheet">
<link href="/static/css/common.css" rel="stylesheet">
<link href="/static/css/override.css" rel="stylesheet">
<link href="/static/css/layout.css" rel="stylesheet">
<link href="/static/css/filebrowser.css" rel="stylesheet">
<link href="/static/css/font-awesome.min.css" rel="stylesheet">
</head>
<body>
<div id="wrapper">
<div id="page-content-wrapper">
<div id="header">
<div id="logo">
<a href="/"></a>
</div>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">로그인</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="/login/">
{% csrf_token %}
<div class="form-group">
<div class="col-md-12">
<label for="userid">아이디</label>
<input id="userid" type="userid" class="form-control" name="username" required autofocus>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="password">비밀번호</label>
<input id="password" type="password" class="form-control" name="password" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-success">
로그인
</button>
<button class="btn btn-success" onclick="location.href='/register/';">
회원가입
</button>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<h5>{{ message }}</h5>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
\ No newline at end of file
{% extends 'layout.html' %}
{% block content %}
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="/register/">
{% csrf_token %}
<div class="form-group">
<div class="col-md-12">
<label for="username"><span style="color:green;">아이디</span></label>
<input id="username" type="text" class="form-control" name="username" required autofocus>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="email"><span style="color:green;">이메일</span><h6 style="display:inline;"> - 비밀번호 분실시 사용됩니다.</h6></label>
<input id="email" type="email" class="form-control" name="email" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="password"><span style="color:green;">비밀번호</span><h6 style="display:inline;"> - 비밀번호는 6자리 이상으로 설정되어야 합니다.</h6></label>
<input id="password" type="password" class="form-control" name="password" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="first_name"><span style="color:green;"></span></label>
<input id="first_name" type="first_name" class="form-control" name="first_name" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label for="last_name"><span style="color:green;">이름</span></label>
<input id="last_name" type="last_name" class="form-control" name="last_name" required>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-success">회원가입</button>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<h6>{{ message }}</h6>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
\ No newline at end of file
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.shortcuts import render, redirect
from django.core.exceptions import PermissionDenied
from khuloud import settings
from khuloud import cognito
from django.views.decorators.csrf import csrf_exempt
import hashlib
import django
def index(request):
if request.user.is_authenticated:
return render(request, "main.html")
else:
return render(request, "login.html")
def login(request):
if request.method == "POST":
if not all(i in request.POST for i in ('username', 'password')):
return render(request, "login.html", {
"message": "please enter id and passowrd"
})
un = request.POST['username']
pw = request.POST['password']
user = authenticate(username=un, password=pw)
if user is not None:
auth = django.contrib.auth.login(request, user)
hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest()
cog = cognito.Cognito()
cog.sign_in_admin(username=un, password=hashcode)
return redirect('/')
else:
return render(request, "login.html", {
"message": "check id and password"
})
else:
return render(request, "login.html")
def logout(request):
if request.user.is_authenticated:
django.contrib.auth.logout(request)
return redirect("/")
def register(request):
Cog = cognito.Cognito()
if request.method == "POST":
require_keys = ('username', 'password', 'first_name', 'last_name', 'email')
if all(i in request.POST for i in require_keys):
if User.objects.filter(username=request.POST['username']).count():
return render(request, 'register.html', {
"message": 'alreay exist id!'
})
if User.objects.filter(email=request.POST['email']).count():
return render(request, 'register.html', {
"message": 'already exist email'
})
userobj = User.objects.create_user(
username=request.POST['username'],
password=request.POST['password'],
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email']
)
hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest()
Cog.sign_up(
username=request.POST['username'],
password=hashcode,
UserAttributes=[
{
'Name' : 'email',
'Value' : request.POST['email'],
},
{
'Name' : 'family_name',
'Value': request.POST['first_name'],
},
{
'Name' : 'given_name',
'Value': request.POST['last_name'],
},
])
Cog.confirm_sign_up(username=request.POST['username']);
return redirect('/')
else:
return render(request, 'register.html', {
"message": 'erroe!'
})
else:
return render(request, 'register.html')
No preview for this file type
No preview for this file type
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
table.put_item(
Item={
'username': 'janedoe',
'first_name': 'Jane',
'last_name': 'Doe',
'age': 25,
'account_type': 'standard_user',
}
)
No preview for this file type
No preview for this file type
"""
Django settings for khuloud project.
Generated by 'django-admin startproject' using Django 1.11.29.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g%eiz-f9vp&g-%12ez#6n57sw60maf7oc^p)0-$jd4n^4grx(l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'.ap-northeast-2.compute.amazonaws.com',
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig',
'login.apps.LoginConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'khuloud.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'khuloud.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
No preview for this file type
"""khuloud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
import blog.views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url('',views.home, name='home'),
url('login/', blog.views.login, name='login'),
url('logout/', blog.views.logout, name='logout'),
url('register/', blog.views.register, name='register'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
No preview for this file type
No preview for this file type
"""
WSGI config for khuloud project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "khuloud.settings")
application = get_wsgi_application()
No preview for this file type
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
# Register your models here.
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class LoginConfig(AppConfig):
name = 'login'
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
No preview for this file type
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import auth
def signup(request):
if request.method=="POST":
if request.POST["password1"]==request.POST["password2"]:
user=User.objects.create_user(
username1=request.POST["username"],
password=request.POST["password1"]
)
auth.login(request,user)
return redirect('login')
return render(request,'signup.html')
return render(request,'signup.html')
def login(request):
if request.method=="POST":
username=request.POST['username']
password=request.POST['password']
user=auth.authenticate(request,username=username,password=password)
if user is not None:
auth.login(request,user)
return redirect('home')
else:
return render(request,'login.html',{'error':'error!'})
else:
return render(request,'login.html')
def logout(request):
auth.logout(request)
return redirect('home')
\ No newline at end of file
No preview for this file type
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "khuloud.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
import boto3
# Get the service resource.
dynamodb = boto3.resource('dynamodb')
# Create the DynamoDB table.
table = dynamodb.create_table(
TableName='users',
KeySchema=[
{
'AttributeName': 'username',
'KeyType': 'HASH'
},
{
'AttributeName': 'last_name',
'KeyType': 'RANGE'
}
],
AttributeDefinitions=[
{
'AttributeName': 'username',
'AttributeType': 'S'
},
{
'AttributeName': 'last_name',
'AttributeType': 'S'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='users')
# Print out some data about the table.
print(table.item_count)