Fakultas Ilmu Komputer UI

Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • kenichi.komala/pkpl-individu-2206081452-kenichikomala
1 result
Select Git revision
Show changes
Commits on Source (5)
Showing
with 176 additions and 113 deletions
# PKPL-Individu-2206081452-KenichiKomala
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.cs.ui.ac.id/kenichi.komala/pkpl-individu-2206081452-kenichikomala.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.cs.ui.ac.id/kenichi.komala/pkpl-individu-2206081452-kenichikomala/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
admin username:admin
admin password:admin#123
\ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
from django.contrib import admin
from django.urls import path
from .views import home
from .views import home, adminonly
app_name = 'home'
urlpatterns = [
path('', home, name="home"),
path('adminonly', adminonly, name="adminonly"),
]
\ No newline at end of file
from django.http import HttpResponse
from django.shortcuts import render
from userauth.models import User
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
if request.GET.get('nama'):
nama = request.GET.get('nama', None)
user = User.objects.get(nama=nama)
return render(request,'home.html', context={'user':user})
return HttpResponse("this is home")
\ No newline at end of file
nama = request.session.get('nama') # Read 'nama' from session
if nama:
try:
user = User.objects.get(nama=nama)
return render(request, 'home.html', context={'user': user})
except User.DoesNotExist:
return HttpResponse("User not found", status=404)
return HttpResponse("this is home")
@user_passes_test(lambda u: u.is_superuser)
def adminonly(request):
return HttpResponse("wow you're admin")
\ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
# Generated by Django 5.1.7 on 2025-03-20 15:54
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userauth', '0002_alter_user_nomor_hp_alter_user_nomor_kartu_atm'),
]
operations = [
migrations.AlterField(
model_name='user',
name='nomor_hp',
field=models.CharField(max_length=17, validators=[django.core.validators.RegexValidator('^(\\d{1} - \\d{7,14}|\\d{2} - \\d{6,13}|\\d{3} - \\d{5,12})$', message='Nomor HP harus dalam format: Kode Negara - Nomor HP (contoh: 62 - 8123456789) dan panjang seluruhnya maksimal 15 karakter')]),
),
migrations.AlterField(
model_name='user',
name='nomor_kartu_atm',
field=models.CharField(max_length=16, validators=[django.core.validators.RegexValidator('^\\d{15,16}$', message='Nomor kartu atm harus sepanjang 15-16 digit')]),
),
]
# Generated by Django 5.1.7 on 2025-03-20 18:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('userauth', '0003_alter_user_nomor_hp_alter_user_nomor_kartu_atm'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
],
),
]
File added
import re
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from django.db import models
from django.core.validators import (
MinLengthValidator, MaxLengthValidator,
......@@ -7,9 +7,35 @@ from django.core.validators import (
)
from django.forms import ValidationError
from django.utils.timezone import now
from datetime import timedelta
from datetime import datetime, timedelta
class User(AbstractUser):
from django.contrib import admin
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(self, nama, email, password=None, **extra_fields):
if not email:
raise ValueError("Email is required")
if not nama:
raise ValueError("Nama is required")
email = self.normalize_email(email)
user = self.model(nama=nama, email=email, **extra_fields)
user.tanggal_lahir = datetime.now()
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, nama, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
return self.create_user(nama, email, password, **extra_fields)
class User(AbstractUser, PermissionsMixin):
objects=UserManager()
STATUS_PEKERJAAN_CHOICES = [
("Karyawan", "Karyawan"),
......@@ -107,4 +133,4 @@ class User(AbstractUser):
super().save(*args, **kwargs)
def __str__(self):
return self.nama
\ No newline at end of file
return self.nama
......@@ -20,6 +20,26 @@
<li>Nomor kartu atm: {{ user.nomor_kartu_atm }}</li>
<li>Status pekerjaan: {{ user.status_pekerjaan }}</li>
</ul>
<script src="" async defer></script>
<button id="logout-btn">Logout</button>
{% if user.is_staff %}<a href="{% url 'home:adminonly' %}">You can click this if you're an admin</a>{% endif %}
<script>
document.getElementById('logout-btn').addEventListener('click', function() {
fetch("{% url 'userauth:logout' %}", {
method: "POST",
headers: { "X-CSRFToken": getCSRFToken() }
}).then(() => window.location.href = "{% url 'userauth:login' %}");
});
function getCSRFToken() {
let cookieValue = null;
document.cookie.split(';').forEach(cookie => {
cookie = cookie.trim();
if (cookie.startsWith("csrftoken=")) {
cookieValue = cookie.substring("csrftoken=".length);
}
});
return cookieValue;
}
</script>
</body>
</html>
\ No newline at end of file
......@@ -11,6 +11,13 @@
<body>
<div class="container">
<div class="row justify-content-center" style="margin-right: 40px;">
{% if warning %}
<p style="color: red;">{{ warning }}</p>
<form action="{% url 'userauth:logout' %}" method="post">
{% csrf_token %}
<button type="submit">Logout First</button>
</form>
{% else %}
<div class="col-lg-6 col-md-12">
<h1 class="text-center" style="margin-bottom: 20px;">Login</h1>
......@@ -31,9 +38,9 @@
{% for message in messages %}
<p>{{message}}</p>
{% endfor %}
<p>Don't have an account yet? <a href="{% url 'register' %}">Register Now</a></p>
<h1> Ini page blm bisa ngapa-ngapain</h1>
<p>Don't have an account yet? <a href="{% url 'userauth:register' %}">Register Now</a></p>
</div>
{%endif%}
</div>
</div>
<script src="" async defer></script>
......
......@@ -15,12 +15,14 @@
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ user_form.as_table }}
{{ user_form.as_table }}
<label for="select-admin" class="form-label">Is Admin :3</label>
<input type="checkbox" name="select-admin" class="form-control">
<tr>
<td></td>
<td><input type="submit" name="submit" value="Daftar"/></td>
</tr>
</table>
</table>
</form>
{% for message in messages %}
<p>{{message}}</p>
......
from django.urls import path
from .views import register, login
from .views import register, login_page, logout_view
app_name = 'userauth'
urlpatterns = [
path("register/", register, name="register"),
path("login/", login, name="login"),
path("login/", login_page, name="login"),
path('logout/', logout_view, name='logout'),
]
\ No newline at end of file
......@@ -2,9 +2,11 @@ from django.urls import reverse
from .forms import UserForm
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from .models import User
# Create your views here.
from django.contrib.auth.decorators import user_passes_test
def register(request):
user_form = UserForm()
......@@ -14,12 +16,56 @@ def register(request):
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user_form.cleaned_data['password'])
is_admin = request.POST.get('select-admin')
if is_admin=="on":
user.is_superuser = True
user.is_staff = True
user.is_active = True
else:
print("tidak masuk")
user.is_superuser = False
user.is_staff = False
user.is_active = False
user.save()
messages.success(request, 'Your account has been successfully created!')
return redirect(f"{reverse('home:home')}?nama={user.nama}")
return redirect(reverse('home:home'))
context = {'user_form':user_form}
return render(request, 'register.html', context)
def login(request):
return render(request, 'login.html')
\ No newline at end of file
# Define a view function for the login page
def login_page(request):
if request.session.get("nama"): # Check if user is already logged in
return render(request, "login.html", {"warning": "You are already logged in. Please log out first."})
# Check if the HTTP request method is POST (form submission)
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# Check if a user with the provided username exists
if not User.objects.filter(username=username).exists():
# Display an error message if the username does not exist
messages.error(request, 'Invalid Username')
return redirect('/login/')
# Authenticate the user with the provided username and password
user = authenticate(username=username, password=password)
if user is None:
# Display an error message if authentication fails (invalid password)
messages.error(request, "Invalid Password")
return redirect('/login/')
else:
# Log in the user and redirect to the home page upon successful login
request.session.flush()
login(request, user)
request.session["nama"] = user.nama
return redirect(reverse('home:home'))
# Render the login page template (GET request)
return render(request, 'login.html')
def logout_view(request):
logout(request)
return redirect('/login/') # Redirect to login page after logout
\ No newline at end of file