Ubuntu

oauth&file_upload

Showing 61 changed files with 248 additions and 166 deletions
1 -# DropBox Project using AWS, Khuloud
2 -
3 -### 경희대학교 Cloud Computing A조
4 -
5 -## 팀원
6 -
7 -- 2017110267 강연욱
8 -
9 -- 2017103972 김성연
10 -
11 -- 2017100907 유정수
12 -
13 -- 2017104025 정수연
14 -
15 -- 2016104173 최재혁
16 -
17 -## 기술 Stack
18 -1. Frontend: nuxt, vuetify
19 -2. Backend : Django
20 -3. Database: DynamoDB
21 -4. A W S : EC2, S3
22 -
23 -## 향후 일정
...\ No newline at end of file ...\ No newline at end of file
No preview for this file type
No preview for this file type
...@@ -59,3 +59,18 @@ class Cognito(): ...@@ -59,3 +59,18 @@ class Cognito():
59 # Get Credentials 59 # Get Credentials
60 response = ci_client.get_credentials_for_identity(IdentityId=response['IdentityId'], Logins={provider: self.token}) 60 response = ci_client.get_credentials_for_identity(IdentityId=response['IdentityId'], Logins={provider: self.token})
61 return response 61 return response
62 + def admin_delete_user(self,username,user_pool_id):
63 +
64 + client= boto3.client('cognito-idp', self.region,
65 +
66 + aws_access_key_id=config['aws']['AWS_ACCESS_KEY_ID'],
67 +
68 + aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY'])
69 +
70 + response = client.admin_delete_user(
71 +
72 + user_pool_id='string',
73 +
74 + username='string')
75 +
76 + return response
......
No preview for this file type
1 +{% extends 'layout.html' %}
2 +
3 +{% block container %}
4 +
5 +
6 +
7 +<h1>User delete</h1>
8 +
9 +<form method="POST">
10 +
11 + <p>정말로 탈퇴하시겠습니까?</p>
12 +
13 + <input type="submit" value="탈퇴"/>
14 +
15 +</form>
16 +
17 +{% endblock %}
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
4 <meta charset="utf-8"> 4 <meta charset="utf-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 6
7 - <title>KHUropBox</title> 7 + <title>Khuloud</title>
8 8
9 <script src="/static/js/app.js"></script> 9 <script src="/static/js/app.js"></script>
10 <script src="/static/js/aws-sdk.min.js"></script> 10 <script src="/static/js/aws-sdk.min.js"></script>
......
1 {% extends 'layout.html' %} 1 {% extends 'layout.html' %}
2 -
3 {% block content %} 2 {% block content %}
4 - 3 +<!--이것을 써줘야 socicalaccount기능을 사용할수있음.-->
4 + {%load socialaccount %}
5 + {% providers_media_js %}
6 + {% load static %}
7 + {% static 'blog/img/naver_login_green.png' as naver_button %}
8 + {% static 'blog/img/naver_login_white.png' as naver_button_hover %}
9 + {% static 'blog/img/google_login_normal.png' as google_button %}
10 + {% static 'blog/img/google_login_preesed.png' as google_button_hover %}
5 <div class="col-md-8 col-md-offset-2"> 11 <div class="col-md-8 col-md-offset-2">
6 <div class="panel panel-default"> 12 <div class="panel panel-default">
7 <div class="panel-heading">로그인</div> 13 <div class="panel-heading">로그인</div>
8 <div class="panel-body"> 14 <div class="panel-body">
9 <form class="form-horizontal" role="form" method="POST" action="/login/"> 15 <form class="form-horizontal" role="form" method="POST" action="/login/">
10 -
11 - {% csrf_token %}
12 <div class="form-group"> 16 <div class="form-group">
13 <div class="col-md-12"> 17 <div class="col-md-12">
14 <label for="userid">아이디</label> 18 <label for="userid">아이디</label>
15 <input id="userid" type="userid" class="form-control" name="username" required autofocus> 19 <input id="userid" type="userid" class="form-control" name="username" required autofocus>
16 </div> 20 </div>
17 </div> 21 </div>
18 -
19 <div class="form-group"> 22 <div class="form-group">
20 <div class="col-md-12"> 23 <div class="col-md-12">
21 <label for="password">비밀번호</label> 24 <label for="password">비밀번호</label>
22 <input id="password" type="password" class="form-control" name="password" required> 25 <input id="password" type="password" class="form-control" name="password" required>
23 </div> 26 </div>
24 </div> 27 </div>
25 -
26 <div class="form-group"> 28 <div class="form-group">
27 <div class="col-md-12"> 29 <div class="col-md-12">
28 <button type="submit" class="btn btn-success"> 30 <button type="submit" class="btn btn-success">
...@@ -32,17 +34,26 @@ ...@@ -32,17 +34,26 @@
32 회원가입 34 회원가입
33 </button> 35 </button>
34 </div> 36 </div>
37 + <a href="{% provider_login_url 'naver' %}">
38 + <img src="{{ naver_button }}"
39 + onmouseover="this.src='{{ naver_button_hover }}'"
40 + onmouseleave="this.src='{{ naver_button }}'"height="34">
41 + </a>
42 + <br>
43 + <a href="{% provider_login_url 'google' %}">
44 + <img src="{{ google_button }}"
45 + onmouseover="this.src='{{ google_button_hover }}'"
46 + onmouseleave="this.src='{{ google_button }}'"height="34">
47 + </a>
48 + <br>
35 </div> 49 </div>
36 -
37 <div class="form-group"> 50 <div class="form-group">
38 <div class="col-md-12 text-center"> 51 <div class="col-md-12 text-center">
39 <h5>{{ message }}</h5> 52 <h5>{{ message }}</h5>
40 </div> 53 </div>
41 </div> 54 </div>
42 -
43 </form> 55 </form>
44 </div> 56 </div>
45 </div> 57 </div>
46 </div> 58 </div>
47 -
48 {% endblock %} 59 {% endblock %}
......
...@@ -3,65 +3,74 @@ from django.contrib.auth import authenticate ...@@ -3,65 +3,74 @@ from django.contrib.auth import authenticate
3 from django.shortcuts import render, redirect 3 from django.shortcuts import render, redirect
4 from django.core.exceptions import PermissionDenied 4 from django.core.exceptions import PermissionDenied
5 from khuloud import settings 5 from khuloud import settings
6 -from khuloud import cognito 6 +from blog import cognito
7 from django.views.decorators.csrf import csrf_exempt 7 from django.views.decorators.csrf import csrf_exempt
8 +from django.http import HttpResponse, JsonResponse
9 +from django.views.decorators.csrf import csrf_exempt
10 +from django.utils.decorators import method_decorator
11 +from rest_framework.response import Response
12 +from rest_framework import status
13 +from cloud import views
8 import hashlib 14 import hashlib
9 - 15 +import json
10 import django 16 import django
11 - 17 +import requests
12 - 18 +@csrf_exempt
13 def main(request): 19 def main(request):
14 if request.user.is_authenticated: 20 if request.user.is_authenticated:
15 return render(request, "main.html") 21 return render(request, "main.html")
16 else: 22 else:
17 return render(request, "login.html") 23 return render(request, "login.html")
18 - 24 +@csrf_exempt
19 def login(request): 25 def login(request):
26 + if request.user.is_authenticated:
27 + raise PermissionDenied
28 + else:
20 if request.method == "POST": 29 if request.method == "POST":
21 - if not all(i in request.POST for i in ('username', 'password')): 30 + data=request.POST
31 + if not all(i in data for i in ('username', 'password')):
22 return render(request, "login.html", { 32 return render(request, "login.html", {
23 - "message": "please enter id and passowrd" 33 + "message": "아이디와 비밀번호를 입력해 주세요"
24 }) 34 })
25 - 35 + un = data['username']
26 - un = request.POST['username'] 36 + pw = data['password']
27 - pw = request.POST['password']
28 -
29 user = authenticate(username=un, password=pw) 37 user = authenticate(username=un, password=pw)
30 -
31 if user is not None: 38 if user is not None:
32 auth = django.contrib.auth.login(request, user) 39 auth = django.contrib.auth.login(request, user)
33 -
34 hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest() 40 hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest()
35 -
36 cog = cognito.Cognito() 41 cog = cognito.Cognito()
37 cog.sign_in_admin(username=un, password=hashcode) 42 cog.sign_in_admin(username=un, password=hashcode)
38 - 43 + return JsonResponse({'user':{
39 - return redirect('/main') 44 + 'username' :un,
45 + 'password' :pw,
46 + }}, safe=False)
40 else: 47 else:
41 return render(request, "login.html", { 48 return render(request, "login.html", {
42 - "message": "check id and password" 49 + "message": "아이디와 비밀번호를 확인해 주세요"
43 }) 50 })
51 +
44 else: 52 else:
45 - return render(request, "login.html")
46 53
54 + return render(request, "login.html")
47 def logout(request): 55 def logout(request):
48 if request.user.is_authenticated: 56 if request.user.is_authenticated:
49 django.contrib.auth.logout(request) 57 django.contrib.auth.logout(request)
50 return redirect("/main") 58 return redirect("/main")
59 +
51 def register(request): 60 def register(request):
52 Cog = cognito.Cognito() 61 Cog = cognito.Cognito()
62 + if request.user.is_authenticated: raise PermissionDenied
53 if request.method == "POST": 63 if request.method == "POST":
54 require_keys = ('username', 'password', 'first_name', 'last_name', 'email') 64 require_keys = ('username', 'password', 'first_name', 'last_name', 'email')
55 if all(i in request.POST for i in require_keys): 65 if all(i in request.POST for i in require_keys):
56 if User.objects.filter(username=request.POST['username']).count(): 66 if User.objects.filter(username=request.POST['username']).count():
57 return render(request, 'register.html', { 67 return render(request, 'register.html', {
58 - "message": 'alreay exist id!' 68 + "message": 'alreadt exist username!'
59 }) 69 })
60 if User.objects.filter(email=request.POST['email']).count(): 70 if User.objects.filter(email=request.POST['email']).count():
61 return render(request, 'register.html', { 71 return render(request, 'register.html', {
62 - "message": 'already exist email' 72 + "message": 'alreadt exist email!'
63 }) 73 })
64 -
65 userobj = User.objects.create_user( 74 userobj = User.objects.create_user(
66 username=request.POST['username'], 75 username=request.POST['username'],
67 password=request.POST['password'], 76 password=request.POST['password'],
...@@ -69,9 +78,7 @@ def register(request): ...@@ -69,9 +78,7 @@ def register(request):
69 last_name=request.POST['last_name'], 78 last_name=request.POST['last_name'],
70 email=request.POST['email'] 79 email=request.POST['email']
71 ) 80 )
72 -
73 hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest() 81 hashcode = hashlib.md5(request.POST['password'].encode('utf-8')).hexdigest()
74 -
75 Cog.sign_up( 82 Cog.sign_up(
76 username=request.POST['username'], 83 username=request.POST['username'],
77 password=hashcode, 84 password=hashcode,
...@@ -89,13 +96,27 @@ def register(request): ...@@ -89,13 +96,27 @@ def register(request):
89 'Value': request.POST['last_name'], 96 'Value': request.POST['last_name'],
90 }, 97 },
91 ]) 98 ])
92 -
93 Cog.confirm_sign_up(username=request.POST['username']); 99 Cog.confirm_sign_up(username=request.POST['username']);
94 - 100 + print(views.create_bucket)
95 return redirect('/main') 101 return redirect('/main')
96 else: 102 else:
97 return render(request, 'register.html', { 103 return render(request, 'register.html', {
98 - "message": 'erroe!' 104 + "message": 'error.'
99 }) 105 })
100 else: 106 else:
101 return render(request, 'register.html') 107 return render(request, 'register.html')
108 +
109 +def delete(request):
110 +
111 + if request.user.is_authenticated:
112 +
113 + if request.method == 'POST':
114 +
115 + request.user.delete()
116 +
117 + return redirect('/main')
118 + else:
119 + return rendet(request,'delete.html',{
120 + "message": 'login required!'
121 + })
122 + return render(request, 'delete.html')
......
No preview for this file type
1 +from django.contrib import admin
2 +
3 +# Register your models here.
1 +from django.apps import AppConfig
2 +
3 +
4 +class CloudConfig(AppConfig):
5 + name = 'cloud'
1 +# Generated by Django 3.0.6 on 2020-05-09 15:45
2 +
3 +from django.db import migrations, models
4 +import django.utils.timezone
5 +
6 +
7 +class Migration(migrations.Migration):
8 +
9 + initial = True
10 +
11 + dependencies = [
12 + ]
13 +
14 + operations = [
15 + migrations.CreateModel(
16 + name='File',
17 + fields=[
18 + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 + ('path', models.CharField(max_length=300)),
20 + ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
21 + ('modified_date', models.DateTimeField(blank=True, null=True)),
22 + ],
23 + ),
24 + ]
1 +from django.db import models
2 +from django.utils import timezone
3 +
4 +# Create your models here.
5 +class File(models.Model):
6 + path=models.CharField(max_length=300)
7 + created_date = models.DateTimeField(default=timezone.now)
8 + modified_date = models.DateTimeField(blank=True, null=True)
...\ No newline at end of file ...\ No newline at end of file
1 +test
...\ No newline at end of file ...\ No newline at end of file
1 +from django.test import TestCase
2 +from rest_framework.test import APIClient
3 +
4 +# Create your tests here.
5 +class APITest(TestCase):
6 + def test_upload_file(self):
7 + client=APIClient()
8 + response=client.post('/files/',{})
9 + self.assertEqual(response.status_code,200)
...\ No newline at end of file ...\ No newline at end of file
1 +from django.urls import path, include
2 +from cloud import views
3 +
4 +urlpatterns = [
5 + path('files/', views.FileView.as_view())
6 +]
...\ No newline at end of file ...\ No newline at end of file
1 +from django.shortcuts import render
2 +from cloud.models import File
3 +from django.views.generic import View
4 +from django.views.decorators.csrf import csrf_exempt
5 +import boto3
6 +from django.http import JsonResponse
7 +#from cloud.aws import aws_key
8 +import configparser
9 +
10 +config = configparser.ConfigParser()
11 +config.read('config.ini')
12 +# class FileToURL(View):
13 +# s3_client = boto3.client(
14 +# 's3',
15 +# aws_access_key_id={''},
16 +# aws_secret_access_key={''}
17 +# )
18 +# @csrf_exempt
19 +# def post(self, request):
20 +# #FILES=MultiValueDict({'file':['/path1.txt','/folder/path2.txt',...]})
21 +# for file in request.FILES.getlist('file'):
22 +# self.s3_client.upload_fileobj(
23 +# file,
24 +# {'khuloud'},
25 +# file.name
26 +# )
27 +# file_urls = [f"https://s3.us-ease-1.amazonaws.com/khuloud/{file.name}" for file in request.FILES.getlist('file')]
28 +
29 +# return JsonResponse({'files':file_urls}, status=200)
30 +
31 +
32 +class FileView(View):
33 + #keys=aws_key()
34 + s3_client = boto3.client(
35 + 's3',
36 + aws_access_key_id = config['aws']['AWS_ACCESS_KEY_ID'],
37 + aws_secret_access_key=config['aws']['AWS_SECRET_ACCESS_KEY']
38 + )
39 +
40 +
41 + @csrf_exempt
42 + def post(self, request):
43 + # filename = request.data.get('filename')
44 + bucket_name = "test-cloudcomputer"
45 + filepath = 'cloud/test/text1.txt'
46 + self.s3_client.upload_file(filepath, bucket_name, filepath)
47 + s3link='https://s3.console.aws.amazon.com/s3/buckets/'+bucket_name+'/'+filepath
48 + return JsonResponse({'file':s3link})
49 +
50 +@csrf_exempt
51 +def create_bucket(request):
52 + s3 = boto3.client('s3')
53 + s3.create_bucket(Bucket='request.user.username')
54 + return Bucket
1 -import boto3
2 -dynamodb = boto3.resource('dynamodb')
3 -table = dynamodb.Table('users')
4 -
5 -table.put_item(
6 -
7 - Item={
8 -
9 - 'username': 'janedoe',
10 -
11 - 'first_name': 'Jane',
12 -
13 - 'last_name': 'Doe',
14 -
15 - 'age': 25,
16 -
17 - 'account_type': 'standard_user',
18 -
19 - }
20 -
21 -)
22 -
23 -
...@@ -28,6 +28,7 @@ DEBUG = True ...@@ -28,6 +28,7 @@ DEBUG = True
28 ALLOWED_HOSTS = [ 28 ALLOWED_HOSTS = [
29 'localhost', 29 'localhost',
30 '.ap-northeast-2.compute.amazonaws.com', 30 '.ap-northeast-2.compute.amazonaws.com',
31 + '54.180.112.94',
31 ] 32 ]
32 33
33 34
...@@ -41,19 +42,42 @@ INSTALLED_APPS = [ ...@@ -41,19 +42,42 @@ INSTALLED_APPS = [
41 'django.contrib.messages', 42 'django.contrib.messages',
42 'django.contrib.staticfiles', 43 'django.contrib.staticfiles',
43 'blog.apps.BlogConfig', 44 'blog.apps.BlogConfig',
44 - 'login.apps.LoginConfig', 45 + 'corsheaders',
46 + 'rest_framework',
47 + 'django.contrib.sites',
48 + 'cloud',
49 + # allauth
50 + 'allauth',
51 + 'allauth.account',
52 + 'allauth.socialaccount',
53 + # provider
54 + 'allauth.socialaccount.providers.naver',
55 + 'allauth.socialaccount.providers.google',
45 ] 56 ]
46 57
47 MIDDLEWARE = [ 58 MIDDLEWARE = [
48 'django.middleware.security.SecurityMiddleware', 59 'django.middleware.security.SecurityMiddleware',
49 'django.contrib.sessions.middleware.SessionMiddleware', 60 'django.contrib.sessions.middleware.SessionMiddleware',
50 'django.middleware.common.CommonMiddleware', 61 'django.middleware.common.CommonMiddleware',
51 - 'django.middleware.csrf.CsrfViewMiddleware', 62 + # 'django.middleware.csrf.CsrfViewMiddleware',
52 'django.contrib.auth.middleware.AuthenticationMiddleware', 63 'django.contrib.auth.middleware.AuthenticationMiddleware',
53 'django.contrib.messages.middleware.MessageMiddleware', 64 'django.contrib.messages.middleware.MessageMiddleware',
54 'django.middleware.clickjacking.XFrameOptionsMiddleware', 65 'django.middleware.clickjacking.XFrameOptionsMiddleware',
66 + 'corsheaders.middleware.CorsMiddleware',
67 + # 'middleware.middleware.DisableCSRF',
68 +
55 ] 69 ]
70 +CORS_ORIGIN_ALLOWED_ALL = True
71 +CORS_ALLOW_CREDENTIALS = True
72 +"""
73 +CORS_ORIGIN_WHITELIST = [
74 +
75 +'http://localhost:3001/',
56 76
77 +'http://127.0.0.1:3001/',
78 +
79 +]
80 +"""
57 ROOT_URLCONF = 'khuloud.urls' 81 ROOT_URLCONF = 'khuloud.urls'
58 82
59 TEMPLATES = [ 83 TEMPLATES = [
...@@ -121,5 +145,13 @@ USE_TZ = True ...@@ -121,5 +145,13 @@ USE_TZ = True
121 145
122 # Static files (CSS, JavaScript, Images) 146 # Static files (CSS, JavaScript, Images)
123 # https://docs.djangoproject.com/en/1.11/howto/static-files/ 147 # https://docs.djangoproject.com/en/1.11/howto/static-files/
148 +AUTHENTICATION_BACKENDS = (
149 + 'django.contrib.auth.backends.ModelBackend',#Needed to login by username in Django admin, regardless of 'allauth'
150 + 'allauth.account.auth_backends.AuthenticationBackend',#'allauth' specific authentication method, such as login by e-mail
124 151
152 +)
125 STATIC_URL = '/static/' 153 STATIC_URL = '/static/'
154 +SITE_ID = 1
155 +LOGIN_REDIRECT_URL = 'main/'
156 +LOGIN_URL = 'login/'
157 +LOGOUT_REDIRECT_URL = 'main/'
......
...@@ -18,10 +18,14 @@ from django.contrib import admin ...@@ -18,10 +18,14 @@ from django.contrib import admin
18 from django.conf import settings 18 from django.conf import settings
19 from django.conf.urls.static import static 19 from django.conf.urls.static import static
20 from django.conf.urls import include, url 20 from django.conf.urls import include, url
21 +from django.urls import path, include
21 urlpatterns = [ 22 urlpatterns = [
22 url(r'^admin/', admin.site.urls), 23 url(r'^admin/', admin.site.urls),
23 url('main/',blog.views.main, name='main'), 24 url('main/',blog.views.main, name='main'),
24 url(r'^login/', blog.views.login, name='login'), 25 url(r'^login/', blog.views.login, name='login'),
25 url(r'^logout/', blog.views.logout, name='logout'), 26 url(r'^logout/', blog.views.logout, name='logout'),
26 url(r'^register/', blog.views.register, name='register'), 27 url(r'^register/', blog.views.register, name='register'),
28 + # url(r'^delete/',blog.views.delete, name='delete'),
29 + url(r'^accounts/', include('allauth.urls')),
30 + path('cloud/',include('cloud.urls'))
27 ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 31 ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
......
1 -import boto3
2 -
3 -
4 -
5 -# Get the service resource.
6 -
7 -dynamodb = boto3.resource('dynamodb')
8 -
9 -
10 -
11 -# Create the DynamoDB table.
12 -
13 -table = dynamodb.create_table(
14 -
15 - TableName='users',
16 -
17 - KeySchema=[
18 -
19 - {
20 -
21 - 'AttributeName': 'username',
22 -
23 - 'KeyType': 'HASH'
24 -
25 - },
26 -
27 - {
28 -
29 - 'AttributeName': 'last_name',
30 -
31 - 'KeyType': 'RANGE'
32 -
33 - }
34 -
35 - ],
36 -
37 - AttributeDefinitions=[
38 -
39 - {
40 -
41 - 'AttributeName': 'username',
42 -
43 - 'AttributeType': 'S'
44 -
45 - },
46 -
47 - {
48 -
49 - 'AttributeName': 'last_name',
50 -
51 - 'AttributeType': 'S'
52 -
53 - },
54 -
55 -
56 -
57 - ],
58 -
59 - ProvisionedThroughput={
60 -
61 - 'ReadCapacityUnits': 5,
62 -
63 - 'WriteCapacityUnits': 5
64 -
65 - }
66 -
67 -)
68 -
69 -
70 -
71 -# Wait until the table exists.
72 -
73 -table.meta.client.get_waiter('table_exists').wait(TableName='users')
74 -
75 -
76 -
77 -# Print out some data about the table.
78 -
79 -print(table.item_count)
80 -
81 -