Initial commit
This commit is contained in:
commit
1d2eb05e8f
13 changed files with 425 additions and 0 deletions
21
LICENSE
Normal file
21
LICENSE
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2022 Tan, kian-ting
|
||||
|
||||
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.
|
||||
39
README.md
Normal file
39
README.md
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# activitypub-server-tutorial-with-django
|
||||
Activitypub server tutorial demo with Django in Python
|
||||
|
||||
modified from https://github.com/timmot/activity-pub-tutorial, and please read it
|
||||
to know how it works similarly.
|
||||
|
||||
(C) 2022 Timothy and Yoxem, under MIT License.
|
||||
|
||||
|
||||
Server config files in Nginx:
|
||||
|
||||
```
|
||||
|
||||
server {
|
||||
server_name orig.social;
|
||||
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
}
|
||||
|
||||
listen 443 ssl; # managed by Certbot
|
||||
ssl_certificate [fullchain.pem]; # managed by Certbot
|
||||
ssl_certificate_key [privkey.pem]; # managed by Certbot
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
|
||||
|
||||
}
|
||||
server {
|
||||
if ($host = orig.social) {
|
||||
return 301 https://$host$request_uri;
|
||||
} # managed by Certbot
|
||||
|
||||
|
||||
listen 80;
|
||||
server_name orig.social;
|
||||
return 404; # managed by Certbot
|
||||
|
||||
```
|
||||
82
send_following_request_script/send_request.py
Normal file
82
send_following_request_script/send_request.py
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
from cryptography.hazmat.backends import default_backend as crypto_default_backend
|
||||
from cryptography.hazmat.primitives import serialization as crypto_serialization
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from urllib.parse import urlparse
|
||||
import base64
|
||||
import datetime
|
||||
import requests
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
target_id = "https://target.social/users/bob"
|
||||
|
||||
recipient_url = target_id
|
||||
recipient_inbox = target_id + "/inbox"
|
||||
|
||||
|
||||
|
||||
sender_url = "https://orig.social/users/alice"
|
||||
sender_key = "https://orig.social/users/alice#main-key"
|
||||
|
||||
activity_id = "https://orig.social/users/alice/follows/test"
|
||||
|
||||
|
||||
# The following is to sign the HTTP request as defined in HTTP Signatures.
|
||||
private_key_text = open('/path/to/private.pem', 'rb').read() # load from file
|
||||
|
||||
private_key = crypto_serialization.load_pem_private_key(
|
||||
private_key_text,
|
||||
password=None,
|
||||
backend=crypto_default_backend()
|
||||
)
|
||||
|
||||
current_date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
|
||||
|
||||
recipient_parsed = urlparse(recipient_inbox)
|
||||
recipient_host = recipient_parsed.netloc
|
||||
recipient_path = recipient_parsed.path
|
||||
|
||||
# Now that the header is set up, we will construct the message
|
||||
follow_request_message = {
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"id": "https://orig.social/users/alice",
|
||||
"type": "Follow",
|
||||
"actor": sender_url,
|
||||
"object": recipient_url
|
||||
}
|
||||
|
||||
# generating digest
|
||||
request_message_json = json.dumps(follow_request_message)
|
||||
digest = base64.b64encode(hashlib.sha256(request_message_json.__str__().encode('utf-8')).digest())
|
||||
|
||||
signature_text = b'(request-target): post %s\ndigest: SHA-256=%s\nhost: %s\ndate: %s' % (recipient_path.encode('utf-8'), digest, recipient_host.encode('utf-8'), current_date.encode('utf-8'))
|
||||
|
||||
raw_signature = private_key.sign(
|
||||
signature_text,
|
||||
padding.PKCS1v15(),
|
||||
hashes.SHA256()
|
||||
)
|
||||
|
||||
signature_header = 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) digest host date",signature="%s"' % (sender_key, base64.b64encode(raw_signature).decode('utf-8'))
|
||||
|
||||
headers = {
|
||||
'Date': current_date,
|
||||
'Content-Type': 'application/activity+json',
|
||||
'Host': recipient_host,
|
||||
'Digest': "SHA-256="+digest.decode('utf-8'),
|
||||
'Signature': signature_header
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
r = requests.post(recipient_inbox, headers=headers, json=follow_request_message)
|
||||
|
||||
a = list(r.iter_content())
|
||||
combined_str = ""
|
||||
for i in a:
|
||||
combined_str += i.decode("ascii")
|
||||
|
||||
print(r)
|
||||
0
simple_server/lianlok/__init__.py
Normal file
0
simple_server/lianlok/__init__.py
Normal file
16
simple_server/lianlok/asgi.py
Normal file
16
simple_server/lianlok/asgi.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
ASGI config for lianlok project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lianlok.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
2
simple_server/lianlok/config.py
Normal file
2
simple_server/lianlok/config.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
site_domain_name = 'orig.social' # change it to your instance domain
|
||||
site_url = 'https://' + site_domain_name
|
||||
125
simple_server/lianlok/settings.py
Normal file
125
simple_server/lianlok/settings.py
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
"""
|
||||
Django settings for lianlok project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 3.2.12.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/3.2/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-uzub$f$dx6n#sht%bv4c$#%)@yqrmzq#*8*yd&=jcix8h#iqo$'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
]
|
||||
|
||||
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 = 'lianlok.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 = 'lianlok.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/3.2/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
27
simple_server/lianlok/urls.py
Normal file
27
simple_server/lianlok/urls.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"""lianlok URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/3.2/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('users/<slug:username>', views.user), #user data
|
||||
path('users/<slug:username>/inbox', views.inbox), #user inbox
|
||||
path('admin/', admin.site.urls),
|
||||
path('.well-known/webfinger', views.webfinger), # web finger
|
||||
path('.well-known/nodeinfo', views.nodeinfo), # node info
|
||||
]
|
||||
75
simple_server/lianlok/views.py
Normal file
75
simple_server/lianlok/views.py
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
from django.http import Http404, HttpResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
import json
|
||||
|
||||
from . import config # import the config variables in the file './config.py'.
|
||||
|
||||
public_key_file = open('public.pem', 'r')
|
||||
public_key = public_key_file.read()
|
||||
|
||||
def user(request, username):
|
||||
user_json = {"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"id": config.site_url + "/users/" + username,
|
||||
"inbox": config.site_url + "/users/" + username + "/inbox",
|
||||
"outbox": config.site_url + "/users/" + username + "/outbox",
|
||||
"type": "Person", # the json for the type
|
||||
"name": username , # user name
|
||||
"preferredUsername": username,
|
||||
"publicKey": {
|
||||
"id": config.site_url + "/users/" + username + "#main-key",
|
||||
"owner": config.site_url + "/users/" + username,
|
||||
"publicKeyPem": public_key
|
||||
}
|
||||
}
|
||||
|
||||
if username != 'john':
|
||||
raise Http404() # throw 404
|
||||
else:
|
||||
# return json file with setting content_type
|
||||
return HttpResponse(json.dumps(user_json), content_type="application/activity+json")
|
||||
|
||||
# send webfinger info
|
||||
def webfinger(request):
|
||||
webfinger = request.GET.get('resource')
|
||||
|
||||
user_name = "john"
|
||||
account = "acct:" + user_name + "@" + config.site_domain_name
|
||||
|
||||
|
||||
if webfinger != account:
|
||||
raise Http404()
|
||||
|
||||
webfinger_json = {
|
||||
"subject": account, # acct:john@example.net
|
||||
"links": [
|
||||
{
|
||||
"rel": "self",
|
||||
"type": "application/activity+json",
|
||||
"href": config.site_url + "/users/" + user_name
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
return HttpResponse(json.dumps(webfinger_json), content_type = "application/activity+json")
|
||||
|
||||
# inbox only accept post
|
||||
@csrf_exempt # naccessary
|
||||
def inbox(request, username):
|
||||
log = open('log.txt', 'a') # store the inbox messages
|
||||
|
||||
if username != 'john':
|
||||
raise Http404()
|
||||
|
||||
else:
|
||||
header = request.headers
|
||||
data = request.body
|
||||
|
||||
text = f'\nmail: {header} \n{data}\n'
|
||||
|
||||
print(text)
|
||||
|
||||
log.write(text)
|
||||
|
||||
log.close()
|
||||
|
||||
return HttpResponse("OK", status="202")
|
||||
16
simple_server/lianlok/wsgi.py
Normal file
16
simple_server/lianlok/wsgi.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
WSGI config for lianlok 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/3.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lianlok.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
22
simple_server/manage.py
Executable file
22
simple_server/manage.py
Executable file
|
|
@ -0,0 +1,22 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lianlok.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
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?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
0
simple_server/private.pem
Normal file
0
simple_server/private.pem
Normal file
0
simple_server/public.pem
Normal file
0
simple_server/public.pem
Normal file
Loading…
Reference in a new issue