Ubuntu

oauth&file_upload

Showing 61 changed files with 251 additions and 169 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
No preview for this file type
......@@ -59,3 +59,18 @@ class Cognito():
# Get Credentials
response = ci_client.get_credentials_for_identity(IdentityId=response['IdentityId'], Logins={provider: self.token})
return response
def admin_delete_user(self,username,user_pool_id):
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_delete_user(
user_pool_id='string',
username='string')
return response
......
No preview for this file type
{% extends 'layout.html' %}
{% block container %}
<h1>User delete</h1>
<form method="POST">
<p>정말로 탈퇴하시겠습니까?</p>
<input type="submit" value="탈퇴"/>
</form>
{% endblock %}
......@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>KHUropBox</title>
<title>Khuloud</title>
<script src="/static/js/app.js"></script>
<script src="/static/js/aws-sdk.min.js"></script>
......@@ -35,4 +35,4 @@
</div>
</div>
</body>
\ No newline at end of file
</body>
......
{% extends 'layout.html' %}
{% block content %}
<!--이것을 써줘야 socicalaccount기능을 사용할수있음.-->
{%load socialaccount %}
{% providers_media_js %}
{% load static %}
{% static 'blog/img/naver_login_green.png' as naver_button %}
{% static 'blog/img/naver_login_white.png' as naver_button_hover %}
{% static 'blog/img/google_login_normal.png' as google_button %}
{% static 'blog/img/google_login_preesed.png' as google_button_hover %}
<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">
......@@ -32,17 +34,26 @@
회원가입
</button>
</div>
<a href="{% provider_login_url 'naver' %}">
<img src="{{ naver_button }}"
onmouseover="this.src='{{ naver_button_hover }}'"
onmouseleave="this.src='{{ naver_button }}'"height="34">
</a>
<br>
<a href="{% provider_login_url 'google' %}">
<img src="{{ google_button }}"
onmouseover="this.src='{{ google_button_hover }}'"
onmouseleave="this.src='{{ google_button }}'"height="34">
</a>
<br>
</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
{% endblock %}
......
......@@ -3,65 +3,74 @@ 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 blog import cognito
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework import status
from cloud import views
import hashlib
import json
import django
import requests
@csrf_exempt
def main(request):
if request.user.is_authenticated:
return render(request, "main.html")
else:
return render(request, "login.html")
@csrf_exempt
def login(request):
if request.user.is_authenticated:
raise PermissionDenied
else:
if request.method == "POST":
if not all(i in request.POST for i in ('username', 'password')):
data=request.POST
if not all(i in data for i in ('username', 'password')):
return render(request, "login.html", {
"message": "please enter id and passowrd"
"message": "아이디와 비밀번호를 입력해 주세요"
})
un = request.POST['username']
pw = request.POST['password']
un = data['username']
pw = data['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('/main')
return JsonResponse({'user':{
'username' :un,
'password' :pw,
}}, safe=False)
else:
return render(request, "login.html", {
"message": "check id and password"
"message": "아이디와 비밀번호를 확인해 주세요"
})
else:
return render(request, "login.html")
return render(request, "login.html")
def logout(request):
if request.user.is_authenticated:
django.contrib.auth.logout(request)
return redirect("/main")
def register(request):
Cog = cognito.Cognito()
if request.user.is_authenticated: raise PermissionDenied
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!'
"message": 'alreadt exist username!'
})
if User.objects.filter(email=request.POST['email']).count():
return render(request, 'register.html', {
"message": 'already exist email'
"message": 'alreadt exist email!'
})
userobj = User.objects.create_user(
username=request.POST['username'],
password=request.POST['password'],
......@@ -69,9 +78,7 @@ def register(request):
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,
......@@ -89,13 +96,27 @@ def register(request):
'Value': request.POST['last_name'],
},
])
Cog.confirm_sign_up(username=request.POST['username']);
print(views.create_bucket)
return redirect('/main')
else:
return render(request, 'register.html', {
"message": 'erroe!'
"message": 'error.'
})
else:
return render(request, 'register.html')
def delete(request):
if request.user.is_authenticated:
if request.method == 'POST':
request.user.delete()
return redirect('/main')
else:
return rendet(request,'delete.html',{
"message": 'login required!'
})
return render(request, 'delete.html')
......
No preview for this file type
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class CloudConfig(AppConfig):
name = 'cloud'
# Generated by Django 3.0.6 on 2020-05-09 15:45
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('path', models.CharField(max_length=300)),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('modified_date', models.DateTimeField(blank=True, null=True)),
],
),
]
from django.db import models
from django.utils import timezone
# Create your models here.
class File(models.Model):
path=models.CharField(max_length=300)
created_date = models.DateTimeField(default=timezone.now)
modified_date = models.DateTimeField(blank=True, null=True)
\ No newline at end of file
test
\ No newline at end of file
from django.test import TestCase
from rest_framework.test import APIClient
# Create your tests here.
class APITest(TestCase):
def test_upload_file(self):
client=APIClient()
response=client.post('/files/',{})
self.assertEqual(response.status_code,200)
\ No newline at end of file
from django.urls import path, include
from cloud import views
urlpatterns = [
path('files/', views.FileView.as_view())
]
\ No newline at end of file
from django.shortcuts import render
from cloud.models import File
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
import boto3
from django.http import JsonResponse
#from cloud.aws import aws_key
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# class FileToURL(View):
# s3_client = boto3.client(
# 's3',
# aws_access_key_id={''},
# aws_secret_access_key={''}
# )
# @csrf_exempt
# def post(self, request):
# #FILES=MultiValueDict({'file':['/path1.txt','/folder/path2.txt',...]})
# for file in request.FILES.getlist('file'):
# self.s3_client.upload_fileobj(
# file,
# {'khuloud'},
# file.name
# )
# file_urls = [f"https://s3.us-ease-1.amazonaws.com/khuloud/{file.name}" for file in request.FILES.getlist('file')]
# return JsonResponse({'files':file_urls}, status=200)
class FileView(View):
#keys=aws_key()
s3_client = boto3.client(
's3',
aws_access_key_id = config['aws']['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY']
)
@csrf_exempt
def post(self, request):
# filename = request.data.get('filename')
bucket_name = "test-cloudcomputer"
filepath = 'cloud/test/text1.txt'
self.s3_client.upload_file(filepath, bucket_name, filepath)
s3link='https://s3.console.aws.amazon.com/s3/buckets/'+bucket_name+'/'+filepath
return JsonResponse({'file':s3link})
@csrf_exempt
def create_bucket(request):
s3 = boto3.client('s3')
s3.create_bucket(Bucket='request.user.username')
return Bucket
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',
}
)
......@@ -28,6 +28,7 @@ DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'.ap-northeast-2.compute.amazonaws.com',
'54.180.112.94',
]
......@@ -41,19 +42,42 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig',
'login.apps.LoginConfig',
'corsheaders',
'rest_framework',
'django.contrib.sites',
'cloud',
# allauth
'allauth',
'allauth.account',
'allauth.socialaccount',
# provider
'allauth.socialaccount.providers.naver',
'allauth.socialaccount.providers.google',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
# 'middleware.middleware.DisableCSRF',
]
CORS_ORIGIN_ALLOWED_ALL = True
CORS_ALLOW_CREDENTIALS = True
"""
CORS_ORIGIN_WHITELIST = [
'http://localhost:3001/',
'http://127.0.0.1:3001/',
]
"""
ROOT_URLCONF = 'khuloud.urls'
TEMPLATES = [
......@@ -121,5 +145,13 @@ USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',#Needed to login by username in Django admin, regardless of 'allauth'
'allauth.account.auth_backends.AuthenticationBackend',#'allauth' specific authentication method, such as login by e-mail
)
STATIC_URL = '/static/'
SITE_ID = 1
LOGIN_REDIRECT_URL = 'main/'
LOGIN_URL = 'login/'
LOGOUT_REDIRECT_URL = 'main/'
......
......@@ -18,10 +18,14 @@ from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url('main/',blog.views.main, name='main'),
url(r'^login/', blog.views.login, name='login'),
url(r'^logout/', blog.views.logout, name='logout'),
url(r'^register/', blog.views.register, name='register'),
url(r'^register/', blog.views.register, name='register'),
# url(r'^delete/',blog.views.delete, name='delete'),
url(r'^accounts/', include('allauth.urls')),
path('cloud/',include('cloud.urls'))
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
......
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)